Golang结构组合-与结构组合无法访问其“父级”

时间:2018-10-02 08:44:24

标签: go struct composition

这个问题似乎是Can embedded methods access "parent" fields?的重复,但是从某种意义上说,我不知道无法访问“父”域;我只是在寻找另一种实现方法的建议,因为我喜欢id结构的想法。


我正在尝试创建一个方便的结构,以使其他结构可以接收一些暂停/取消暂停方法。

想象一下:

可行结构

input

由可暂停组成的结构

现在,在我的其他结构上,我想覆盖id方法,以便除了更改 const xhr = new XMLHttpRequest() xhr.open('POST', url, true); xhr.withCredentials = false; xhr.onprogress = function () { console.log('LOADING', xhr.status); csvContent += xhr.responseText + '\r\n'; } xhr.onload = function () { console.log('DONE', xhr.status); const encodedUri = encodeURI(csvContent); const link = document.createElement('a'); link.setAttribute('href', encodedUri); link.setAttribute('download', 'my_data'); document.body.appendChild(link); // Required for FF link.click(); }; xhr.send(JSON.stringify(requestPayload)); 的值之外,还会发生其他一些事情。

Pausable

问题

问题就变成了这个。我想向type Pausable struct { isPaused bool } func (p *Pausable) Pause() { p.isPaused = true } func (p *Pausable) Unpause() { p.isPaused = false } 结构中添加一个Unpause()方法,以便它成为

p.isPaused

但是,如果超时超时,则会在type Mystruct struct { Pausable // Composition } func (s *Mystruct) Unpause() { s.Unpause() // Do other stuff } 而不是PauseUntil()上调用Pausable。解决这个问题的聪明方法是什么?

1 个答案:

答案 0 :(得分:1)

您可以使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)
相关问题