Struct conversion with methods in golang

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

Struct conversion with methods in golang

问题

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

这是我正在寻找的:

  1. type foo struct {
  2. a int
  3. }
  4. func (f *foo) bar() {
  5. f.a = 42
  6. }
  7. type foo2 foo
  8. func main() {
  9. f := foo{12}
  10. f.bar()
  11. f2 := foo2(f)
  12. f2.a = 0
  13. f2.bar()
  14. fmt.Println(f)
  15. fmt.Println(f2)
  16. }

在"f2.Bar()"这一行,我得到了错误:

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

我该如何做才能在进行转换后仍然可以访问Bar方法?我希望我的输出是:

  1. {42}
  2. {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 :

  1. type foo struct {
  2. a int
  3. }
  4. func (f *foo) bar() {
  5. f.a = 42
  6. }
  7. type foo2 foo
  8. func main() {
  9. f := foo{12}
  10. f.bar()
  11. f2 := foo2(f)
  12. f2.a = 0
  13. f2.bar()
  14. fmt.Println(f)
  15. fmt.Println(f2)
  16. }

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

  1. {42}
  2. {42}

答案1

得分: 2

你可以使用struct embedding

  1. package main
  2. import (
  3. "fmt"
  4. )
  5. type foo struct {
  6. a int
  7. }
  8. func (f *foo) bar() {
  9. f.a = 42
  10. }
  11. type foo2 struct {
  12. foo
  13. }
  14. func main() {
  15. f := foo{12}
  16. f.bar()
  17. f2 := foo2{}
  18. f2.a = 0
  19. f2.bar()
  20. fmt.Println(f)
  21. fmt.Println(f2)
  22. }

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

  1. type foo2 struct {
  2. foo
  3. }

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

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

  1. {42}
  2. {{42}}

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

英文:

You can use struct embeding

  1. package main
  2. import (
  3. "fmt"
  4. )
  5. type foo struct {
  6. a int
  7. }
  8. func (f *foo) bar() {
  9. f.a = 42
  10. }
  11. type foo2 struct {
  12. foo
  13. }
  14. func main() {
  15. f := foo{12}
  16. f.bar()
  17. f2 := foo2{}
  18. f2.a = 0
  19. f2.bar()
  20. fmt.Println(f)
  21. fmt.Println(f2)
  22. }

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

  1. type foo2 struct {
  2. foo
  3. }

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

Note that output of this program will be:

  1. {42}
  2. {{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:

确定