【问题标题】:Struct conversion with methods in golang使用golang中的方法进行结构转换
【发布时间】:2017-07-14 19:20:09
【问题描述】:

为了简化项目的导入和依赖关系,我想转换类型结构并仍然可以访问它所附加的所有方法。

这就是我要找的:

type foo struct {
a int
}

func (f *foo) bar() {
    f.a = 42
}

type foo2 foo

func main() {
    f := foo{12}
    f.bar()
    f2 := foo2(f)
    f2.a = 0
    f2.bar()
    fmt.Println(f)
    fmt.Println(f2)
}

在“f2.Bar()”行我得到错误:

“f2.Bar 未定义(类型 Foo2 没有字段或方法 Bar)”

即使我进行了转换,如何才能访问方法 Bar。我希望我的输出是

{42}
{42}

【问题讨论】:

    标签: go methods struct type-conversion


    【解决方案1】:

    您可以使用struct embeding

    package main
    
    import (
        "fmt"
    )
    
    type foo struct {
        a int
    }
    
    func (f *foo) bar() {
        f.a = 42
    }
    
    type foo2 struct {
        foo
    }
    
    func main() {
        f := foo{12}
        f.bar()
        f2 := foo2{}
        f2.a = 0
        f2.bar()
        fmt.Println(f)
        fmt.Println(f2)
    }
    

    只需创建 struct 并将 foo 作为其成员之一。不要给它明确的名字

    type foo2 struct {
        foo
    }
    

    这样 foo 的所有方法都可用于 foo2。

    请注意,此程序的输出将是:

    {42}
    {{42}}
    

    新的 Go 1.9 将提供更有效的方法来实现我想你想做的事情:https://tip.golang.org/doc/go1.9#language

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多