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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?