Golang 结构组合 - 用结构组合无法访问其 "parent"

Golang struct composition - composed with struct cannot access its "parent"

这个问题似乎是 Can embedded methods access "parent" fields? 的重复问题,但并不是我知道无法访问 "parent" 字段的意思;我只是在寻找另一种方法的建议,因为我喜欢 Pausable 结构的想法。


我正在尝试制作一个方便的结构,使其他结构能够接收一些 pausing/unpausing 方法。

想象一下:

可暂停结构

type Pausable struct {
    isPaused bool
}

func (p *Pausable) Pause() {
    p.isPaused = true
}

func (p *Pausable) Unpause() {
    p.isPaused = false
}

与Pausable

组合的结构体

现在在我的其他结构上,我想覆盖 Unpause() 方法,这样除了更改 p.isPaused 的值外,还会发生其他一些事情。

type Mystruct struct {
    Pausable // Composition
}

func (s *Mystruct) Unpause() {
    s.Unpause()

    // Do other stuff
}

问题

问题就变成了这样。我想在 Pausable 结构中添加一个 PauseUntil() 方法,这样它就变成了

type Pausable struct {
    isPaused bool
}

func (p *Pausable) Pause() {
    p.isPaused = true
}

func (p *Pausable) Unpause() {
    p.isPaused = false
}

func (p *Pausable) PauseUntil(dur time.Duration) {
    p.Pause()

    go func() {
        time.Sleep(dur)
        p.Unpause()
    }()
}

但是,当超时用完时,Unpause() 会在 Pausable 上调用,而不是在 Mystruct 上调用。解决这个问题的聪明方法是什么?

您可以使 PauseUntil 成为在 Pauser 接口上运行的函数。

例如

type Pauser interface {
    Pause()
    Unpause()
}

func PauseUntil(p Pauser) {
    p.Pause()

    go func() {
        time.Sleep(dur)
        p.Unpause()
    }()
}

那么您应该能够将您的 myStruct 传递给该函数:

ms := new(myStruct)
PauseUntil(ms)