Struct conversion with methods in golang

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

Struct conversion with methods in golang

问题

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

这是我正在寻找的:

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}
英文:

In order to simplify imports and dependencies for a project, I would like to convert a type struct and still have access to all the methods it is attached to.

This is what I am looking for :

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

On the line "f2.Bar()" I get the error :

"f2.Bar undefined (type Foo2 has no field or method Bar)"

How can I do to have access to the method Bar even if I made a conversion. I would like my output to be

{42}
{42}

答案1

得分: 2

你可以使用struct embedding

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

只需创建一个结构体,并将foo作为其成员之一,不需要为其指定显式名称。

type foo2 struct {
	foo
}

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

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

{42}
{{42}}

更有效地实现您想要做的事情的方法将在新的Go 1.9版本中推出:https://tip.golang.org/doc/go1.9#language

英文:

You can use 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)
}

Just create struct and use foo as one of its members. Don't give it explicit name

type foo2 struct {
	foo
}

That way all methods of foo will be available for foo2.

Note that output of this program will be:

{42}
{{42}}

More effective way of achieving what I suppose you want to do, will come with new Go 1.9: https://tip.golang.org/doc/go1.9#language

huangapple
  • 本文由 发表于 2017年7月15日 03:20:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/45110223.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定