Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass interface pointer through a function in Golang?

Tags:

interface

go

I was testing golang functionalities and came across this concept where I can use a pointer of an interface as an interface itself. In the below code, how do I ensure that the value of one changes to random.

package main

import (
    "fmt"
)

func some(check interface{}) {
    check = "random"
}

func main() {
    var one *interface{}
    some(one)
    fmt.Println(one)
}

Specifically, I need ways in which I can pass an interface pointer to a function which accepts an interface as an argument.

Thanks!

like image 958
re3el Avatar asked Oct 31 '25 15:10

re3el


1 Answers

  1. Accept a pointer to interface{} as the first parameter to some
  2. Pass the address of one to some
package main

import (
    "fmt"
)

func some(check *interface{}) {
    *check = "random"
}

func main() {
    var one interface{}
    some(&one)
    fmt.Println(one)
}

https://play.golang.org/p/ksz6d4p2f0

If you want to keep the same signature of some, you will have to use the reflect package to set the interface{} pointer value:

package main

import (
    "fmt"
    "reflect"
)

func some(check interface{}) {
    val := reflect.ValueOf(check)
    if val.Kind() != reflect.Ptr {
        panic("some: check must be a pointer")
    }
    val.Elem().Set(reflect.ValueOf("random"))
}

func main() {
    var one interface{}
    some(&one)
    fmt.Println(one)
}

https://play.golang.org/p/ocqkeLdFLu

Note: val.Elem().Set() will panic if the value passed is not assignable to check's pointed-to type.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!