re3el
re3el

Reputation: 785

How to pass interface pointer through a function in Golang?

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!

Upvotes: 4

Views: 12194

Answers (1)

user142162
user142162

Reputation:

  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.

Upvotes: 12

Related Questions