在Go中重新分配方法

时间:2014-09-26 03:01:46

标签: 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中的等价物是什么?

1 个答案:

答案 0 :(得分: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() //uncomment to call the original m1.
}

func doI1(i I1) {
    i.m1()
}

func main() {
    doI1(S1{})
    doI1(S2{S1{}})
}

play

相关问题