登录
首页 >  Golang >  Go问答

工厂模式中的结构体继承

来源:stackoverflow

时间:2024-04-17 12:00:36 271浏览 收藏

编程并不是一个机械性的工作,而是需要有思考,有创新的工作,语法是固定的,但解决问题的思路则是依靠人的思维,这就需要我们坚持学习和更新自己的知识。今天golang学习网就整理分享《工厂模式中的结构体继承》,文章讲解的知识点主要包括,如果你对Golang方面的知识点感兴趣,就不要错过golang学习网,在这可以对大家的知识积累有所帮助,助力开发能力的提升。

问题内容

我需要为某些结构创建继承者:

// not interface, pure struct
type base struct {
  a int
  b string
}

type child struct {
  base
  c bool
}

func (c *child) someloop() {
  for {
    // business logic
  }
}

创建子实例并从工厂返回

func maker() *base {
  child := &child {
    base {
      a: 1
      b: "2"
    },
    c: false,
  }
  go child.some()
  return child
}

从工厂使用作为具有字段 a 和 b 的基本结构的对象

o := maker()
fmt.Println(o.A, o.B)

但我无法从 maker 函数将 child 作为 base 返回。如何实现这个模式?


解决方案


golang没有继承,只有嵌入。您无法从 maker()child 返回为 *base。但是,您可以返回&child.base(在过程中的返回值中丢失指向child的链接)。

最接近您想要的就是为 base 定义一个 interface{},并具有返回 ab 值的“能力”(函数):

type baseinterface interface { // don't actually name it like this
    // you would usually omit the "get", but then
    // we'd get a name conflict with the fields later.
    // this may be avoided by making them lowercase, i.e. private.
    geta() int
    getb() string
}

然后,您可以为 *child 实现此功能:

// note how this implements baseinterface for child and *child alike.

func (child *child) geta() int {
    return child.a
}

func (child *child) getb() string {
    return child.b
}

然后,您可以将其返回为 baseinterface,如果需要,稍后进行类型断言以获取 *child 的原始类型:

returnedValue.(*Child) // Yes, this really is what the syntax looks like.

这有时是必要的,rob pike(golang 的创始人之一)在 a talk at dotGo 2015 期间承认这是他们不引以为豪的语言的方面之一。要点是不要试图在代码中引入复杂性该语言旨在避免这种情况。

好了,本文到此结束,带大家了解了《工厂模式中的结构体继承》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多Golang知识!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>