使用Golang中的方法进行结构转换

带领TheSalt:

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

这是我正在寻找的:

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)”

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

{42}
{42}
拉多斯瓦夫·扎乌斯卡(RadoslawZałuska):

您可以使用结构嵌入

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
}

这样,foo2的所有方法都将可用。

请注意,该程序的输出为:

{42}
{{42}}

新的Go 1.9随附了实现我想做的更有效的方法:https : //tip.golang.org/doc/go1.9#language

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章