dstxpei5823 2017-03-31 19:07
浏览 100
已采纳

在golang中,如何为现有struct对象分配方法?

I was wondering if doing something like this in golang is even possible --

type MyStruct struct {
    id int
}

func (ms *MyStruct) PrintHello() {
    fmt.Printf("Hello from original method %v", ms.id)
}

func main() {
    fmt.Println("Hello, playground")
    m := MyStruct{}
    m.PrintHello()

    m.PrintHello = func() {fmt.Printf("Hello from newer method 2")}
}

Error: cannot assign to m.PrintHello

https://play.golang.org/p/2oJQFFH4O5

Sorry if this doesn't make sense for Go programmers, I am new to Go and wondering if some of the things that can be done in dynamically typed languages can be done in Go. Thanks! :-)

  • 写回答

1条回答 默认 最新

  • duanmei2805 2017-03-31 19:21
    关注

    Given that Go is a statically typed language, you cannot do this specific piece of code. However, functions are variables, so you CAN do something like this. Just remember that this is technically NOT the same as assigning a new method, as JimB states in the comments.

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

    package main
    
    import (
        "fmt"
    )
    
    type MyStruct struct {
        id         int
        PrintHello func(ms * MyStruct)
    }
    
    func (ms *MyStruct) init() {
        ms.PrintHello = func(ms *MyStruct) { fmt.Printf("Hello from original method %v
    ", ms.id) }
    }
    
    func main() {
        m := &MyStruct{id: 42}
        m.init()
        m.PrintHello(m)
    
        m.PrintHello = func(ms *MyStruct) { fmt.Printf("Hello from newer method 2 %d
    ", ms.id) }
        m.PrintHello(m)
    }
    

    Because this function is not really a method, you can only access the internal struct values by passing it as an argument. This means that if this ever has to cross package boundaries, unexported values will not be available.

    It is also important to note that the function type needs to be the same. So if you defined the function as PrintHello func(ms * MyStruct) error in the struct, you would need to assign a function that returns an error.

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

报告相同问题?

悬赏问题

  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥15 Python3.5 相关代码写作
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗