重新分配Go中的方法

huangapple go评论161阅读模式
英文:

Re-assigning methods in Go

问题

假设我有以下代码:

  1. package main
  2. import "fmt"
  3. type I1 interface {
  4. m1()
  5. }
  6. func f1() {
  7. fmt.Println("dosomething")
  8. }
  9. func main() {
  10. var obj I1
  11. obj.m1 = f1
  12. obj.m1()
  13. }

这会生成错误:

  1. ./empty.go:16: cannot assign to obj.m1

为什么我不能赋值给"方法字段"?

在C语言中,我可以传递函数指针。在Go语言中有什么等效的方法吗?

英文:

Suppose I have the following:

  1. package main
  2. import "fmt"
  3. type I1 interface {
  4. m1()
  5. }
  6. func f1() {
  7. fmt.Println("dosomething")
  8. }
  9. func main() {
  10. var obj I1
  11. obj.m1 = f1
  12. obj.m1()
  13. }

This generates the error

  1. ./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

你不能将函数分配给接口,但可以将其分配给结构体,例如:

  1. type S1 struct {
  2. m1 func()
  3. }
  4. func f1() {
  5. fmt.Println("dosomething")
  6. }
  7. func main() {
  8. var obj S1
  9. obj.m1 = f1
  10. obj.m1()
  11. }

// 另一个例子

  1. type I1 interface {
  2. m1()
  3. }
  4. type S1 struct {}
  5. func (S1) m1() {
  6. fmt.Println("dosomething")
  7. }
  8. type S2 struct { S1 }
  9. func (s S2) m1() {
  10. fmt.Println("dosomething-2")
  11. //s.S1.m1() //取消注释以调用原始的m1。
  12. }
  13. func doI1(i I1) {
  14. i.m1()
  15. }
  16. func main() {
  17. doI1(S1{})
  18. doI1(S2{S1{}})
  19. }

play

英文:

You can't assign a function to an interface, you can do it for a struct, for example:

  1. type S1 struct {
  2. m1 func()
  3. }
  4. func f1() {
  5. fmt.Println("dosomething")
  6. }
  7. func main() {
  8. var obj S1
  9. obj.m1 = f1
  10. obj.m1()
  11. }

// another example

  1. type I1 interface {
  2. m1()
  3. }
  4. type S1 struct {}
  5. func (S1) m1() {
  6. fmt.Println("dosomething")
  7. }
  8. type S2 struct { S1 }
  9. func (s S2) m1() {
  10. fmt.Println("dosomething-2")
  11. //s.S1.m1() //uncomment to call the original m1.
  12. }
  13. func doI1(i I1) {
  14. i.m1()
  15. }
  16. func main() {
  17. doI1(S1{})
  18. doI1(S2{S1{}})
  19. }

<kbd>play</kbd>

huangapple
  • 本文由 发表于 2014年9月26日 11:01:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/26051389.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定