英文:
Re-assigning methods in Go
问题
假设我有以下代码:
package main
import "fmt"
type I1 interface {
m1()
}
func f1() {
fmt.Println("dosomething")
}
func main() {
var obj I1
obj.m1 = f1
obj.m1()
}
这会生成错误:
./empty.go:16: cannot assign to obj.m1
为什么我不能赋值给"方法字段"?
在C语言中,我可以传递函数指针。在Go语言中有什么等效的方法吗?
英文:
Suppose I have the following:
package main
import "fmt"
type I1 interface {
m1()
}
func f1() {
fmt.Println("dosomething")
}
func main() {
var obj I1
obj.m1 = f1
obj.m1()
}
This generates the error
./empty.go:16: cannot assign to obj.m1
Why can't I assign to 'method fields'?
In C, I can just pass around function pointers. What is the equivalent in Go?
答案1
得分: 2
你不能将函数分配给接口,但可以将其分配给结构体,例如:
type S1 struct {
m1 func()
}
func f1() {
fmt.Println("dosomething")
}
func main() {
var obj S1
obj.m1 = f1
obj.m1()
}
// 另一个例子
type I1 interface {
m1()
}
type S1 struct {}
func (S1) m1() {
fmt.Println("dosomething")
}
type S2 struct { S1 }
func (s S2) m1() {
fmt.Println("dosomething-2")
//s.S1.m1() //取消注释以调用原始的m1。
}
func doI1(i I1) {
i.m1()
}
func main() {
doI1(S1{})
doI1(S2{S1{}})
}
英文:
You can't assign a function to an interface, you can do it for a struct, for example:
type S1 struct {
m1 func()
}
func f1() {
fmt.Println("dosomething")
}
func main() {
var obj S1
obj.m1 = f1
obj.m1()
}
// another example
type I1 interface {
m1()
}
type S1 struct {}
func (S1) m1() {
fmt.Println("dosomething")
}
type S2 struct { S1 }
func (s S2) m1() {
fmt.Println("dosomething-2")
//s.S1.m1() //uncomment to call the original m1.
}
func doI1(i I1) {
i.m1()
}
func main() {
doI1(S1{})
doI1(S2{S1{}})
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论