dsfasdfsda234234 2017-12-12 04:44
浏览 51
已采纳

如何通过地址传递给带接口的功能

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!

  • 写回答

1条回答 默认 最新

  • dqab0824 2017-12-12 05:32
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法