Search code examples
pointersgotypesinterfacetype-assertion

How to pass by address to function that takes interface


I have a Character interface defined like:

type Character interface {
    SomeFunction()
}

And a Player struct defined like:

type Player struct{}

func (r *Player) SomeFunction() { }
// Some fields and other functions....

Suppose I have a function defined as

func TakeInterface(characterValue Character) {
     // Do something
}

The catch is, I want to pass in characterValue as a Player by address so that changes made to it will be made to the Player the caller passed in. In Java and C++, this is easy, but I can't seem to figure it out in Golang. I've tried something like,

func TakeInterface(characterValue &Character) {
    // Do something that changes characterValue
}

and then passing in a Player pointer, but then I get the error *Character.Character is pointer to interface, not interface when I try to pass in an address.

How do I go about passing a Player by address to a function that takes a Character/Character pointer? I've been looking around but with no success. Thanks!


Solution

  • Have you tested your code? I'm guessing no, because it works the way you expect it to work. Just pass a pointer to a player when calling the function.

    func main() {
        p := new(Player)
        TakeInterface(p)
    }
    

    Or

    func main() {
        p := Player{0}
        TakeInterface(&p)
    }
    

    In go you can use a type or a pointer to a type as an argument to a function that takes an interface because both satisfy the interface. You can do both:

        var p1 Player
        p1.SomeFunction()
        var p2 *Player
        p2.SomeFunction()
    

    You should do the tour of go: https://tour.golang.org/methods/10

    Here is the whole code: https://play.golang.org/p/iQIChLCziG