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.

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

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效