用作结构体字段或结构体方法

Tha*_*ove 9 methods struct function go

有人可以帮助我澄清在哪些情况下最好使用函数作为结构体字段以及何时作为结构体方法?

icz*_*cza 13

函数类型的字段不是方法,因此它不是结构类型的方法集的一部分。使用结构类型作为接收者声明的“true”方法将成为方法集的一部分。

话虽这么说,如果你想实现一个接口,你别无选择,只能定义“真正的”方法。

方法“附加”到具体类型并且不能在运行时更改。函数类型的字段可以用来“模仿”虚拟方法,但如上所述,这不是方法。函数类型的字段可以在运行时重新分配。

就像这个例子一样:

type Foo struct {
    Bar func()
}

func main() {
    f := Foo{
        Bar: func() { fmt.Println("initial") },
    }
    f.Bar()

    f.Bar = func() { fmt.Println("changed") }
    f.Bar()
}
Run Code Online (Sandbox Code Playgroud)

哪个输出(在Go Playground上尝试):

initial
changed
Run Code Online (Sandbox Code Playgroud)

函数类型的字段通常用于存储回调函数。标准库中的示例是 http.Serverhttp.Transport