重新分配Go中的方法

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

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{}})
}

play

英文:

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{}})
}

<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:

确定