共享嵌入结构的领域逻辑

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

Sharing Domain Logic for Embedded Structs

问题

我有一些结构体,它们共享一些公共属性和逻辑,但我找不到一种能够共享逻辑的方法。基本上,我有一个作为包的一部分处理“小部件”的文件。我想要有一个通用的Widget结构体,它嵌入在每个指定的小部件结构体WidgetAWidgetB中,并在创建过程中共享一些逻辑。例如:

type Widget struct {
    name string
}
type WidgetA struct {
    Widget
    inspector string
}
type WidgetB struct {
    Widget
    length int
    height int
}

func (w *Widget) Init() {
    // 做一些共享的事情
    // 然后确定这个小部件的类型,并委托给相应的接收函数
}
func (wa *WidgetA) Create () { ... }
func (wb *WidgetB) Create () { ... }

在调用端,可能像这样:

widgetA := &WidgetA{}
widgetA.Init()

我找不到在Go语言中共享逻辑的解决方案,所以我想要么理解我哪里出错了,要么如果我试图应用不适合的旧习惯,找出使用Go语言实现相同目标的最惯用的方法。

期待您的见解!

英文:

I have a number of structs that share some common properties and logic, but I haven't been able to find a way to share logic that works. Basically, I have a file as part of a package that handles "widgets". I wanted to have a general Widget struct that's embedded in each specified widget struct WidgetA and WidgetB, then share a bit of logic during the creation process. For example:

type Widget struct {
    name string
}
type WidgetA struct {
    Widget
    inspector string
}
type WidgetB struct {
    Widget
    length int
    height int
}

func (w *Widget) Init() {
    // Do some shared things
    // Then figure out which _type_ of Widget this is and delegate
    // to the appropriate receiver function
}
func (wa *WidgetA) Create () { ... }
func (wb *WidgetB) Create () { ... }

On the calling end, maybe something like this:

widgetA := &WidgetA{}
widgetA.Init()

I can't find a working solution to share the logic in Go, so I'd like to either understand where I'm going wrong or, if I'm going wrong be trying to apply old habits where they don't belong, figure out the most idiomatic way of accomplishing the same goal using Go.

Insight appreciated!

答案1

得分: 4

你可以这样做:

func (w *Widget) Init() {...}

func (wa *WidgetA) Init() {
   wa.Widget.Init()
   // 初始化 WidgetA
}

func (wb *WidgetB) Init() {
   wb.Widget.Init()
   // 初始化 WidgetB
}


widgetA := WidgetA{}
widgetA.Init() 

如果你不知道要初始化的对象的类型,你可以使用接口:

type Initer interface {
   Init()
}

func f(w Initer) {
  w.Init() // 调用底层 widget 类型的 Init() 方法
}
英文:

You can do something like this:

func (w *Widget) Init() {...}

func (wa *WidgetA) Init() {
   wa.Widget.Init()
   // init widgetA
}

func (wb *WidgetB) Init() {
   wb.Widget.Init()
   // init widgetB
}


widgetA:=WidgetA{}
widgetA.Init() 

If you don't know the type of the object you're initializing, you can use an interface:

type Initer interface {
   Init()
}

func f(w Initer) {
  w.Init() // Call the Init() for the underlying widget type
}

huangapple
  • 本文由 发表于 2021年8月11日 00:23:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/68730381.html
匿名

发表评论

匿名网友

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

确定