Go:结构中的方法和方法切片

时间:2014-02-28 13:56:45

标签: object methods struct go slice

是否可以创建方法切片或方法指针切片并将它们存储在结构中的字段中?

以下是问题的一个示例:

package main

import (
  "fmt"
)

type Foo struct {
  fooFunc func() /// Problem here
  name string
  age int
}

type Bar struct {
  barFunc []func() /// Problem here.
  salary int
  debt int
}

func main() {

  fooObject := Foo{name: "micheal",
             fooFunc: testFunc}

  fooObject.fooFunc() 

  fooObject = Foo{name: "lisa",
          age : 22,
          fooFunc: testFunc2}

  fooObject.fooFunc() 


  barFuncList := make([]func(), 2,2)
  barFuncList[0] = barSalary
  barFuncList[1] = barDebt

  barObject := Bar{name: fooObject.name,
           salary: 45000,
           debt: 200,
           barFunc: barFuncList)

  for i := 0; i < len(barObject.barFunc); i++{  // This is what I really want to do
    barObject.barFunc[i]
  }
}

func (bar *Foo) testfunc() {
  fmt.Println(bar.name)
}

func (bar *Foo) testfunc2() {
  fmt.Println("My name is ", bar.name , " and my age is " , bar.age)
}

func (foo *Bar) barSalary() {
  fmt.Println(" My salary is " , foo.salary)
}

func (foo *Bar) barDebt() {
  fmt.Println(" My salary is " , foo.debt)
}

有没有办法将对象的方法附加到其结构的字段?

是否也可以将对象方法的一部分放在其结构的字段中?

2 个答案:

答案 0 :(得分:1)

Go isn不能进行猴子修补(万岁!),但如果你真的想要,可以从对象方法进行动态函数调用。我修改(并修复了)你的代码只是为了表明这一点。

http://play.golang.org/p/2rwCW2N93-

package main

import (
  "fmt"
)

type FF func(*Foo)

type Foo struct {
  foofunc FF
  name string
  age int
}

func foo1(f *Foo) {
        fmt.Println("[foo1]", f.name)
}

func foo2(f *Foo) {
        fmt.Println("[foo2] My name is ", f.name , " and my age is " , f.age)
}


type BB func(*Bar)

type Bar struct {
  barFuncs []BB
  salary int
  debt int
}

func barSalary(b *Bar) {
        fmt.Println("[barSalary] My salary is " , b.salary)
}

func barDebt(b *Bar) {
        fmt.Println("[barDebt] My salary is ", b.debt)
}

func main() {

        fooObject := Foo{
                name: "micheal",
        }
        fooObject.foofunc = foo1

        fooObject.foofunc(&fooObject)

        fooObject = Foo{
                name: "lisa",
                age : 22,
        }
        fooObject.foofunc = foo2

        fooObject.foofunc(&fooObject)



        barFuncList := make([]BB, 2, 2)
        barFuncList[0] = barSalary
        barFuncList[1] = barDebt

        barObject := Bar{
                salary: 45000,
                debt: 200,
                barFuncs: barFuncList,
        }

        for i := 0; i < len(barObject.barFuncs); i++ {
                barObject.barFuncs[i](&barObject)
        }
}

答案 1 :(得分:0)

我认为您不能动态更新结构字段的方法,但可以在interfaces上动态调度方法。