doucai6663 2017-11-09 01:26
浏览 8
已采纳

计时器具有一个名为C的chan字段。要返回它,我必须在其后加上括号吗?

I'm a Go rookie.

I'm looking at some Kubernetes source code that looks in part like this:

t := r.clock.NewTimer(r.resyncPeriod)
return t.C(), t.Stop

t is a new Timer, and I can see that the Timer type has a field named C, which is a chan whose messages, should there be any, will be of type Time. I understand that part.

I don't understand why it's t.C() above, and not t.C (no parentheses). To my naïve eyes, this looks like some sort of function invocation on the channel. Could someone kindly explain what's going on here? What do the parentheses indicate, in particular? Thank you.

  • 写回答

1条回答 默认 最新

  • dro80463 2017-11-09 02:02
    关注

    If you look at Clock

    you will find:

    type Clock interface {
        Now() time.Time
        Since(time.Time) time.Duration
        After(d time.Duration) <-chan time.Time
        NewTimer(d time.Duration) Timer
        Sleep(d time.Duration)
        Tick(d time.Duration) <-chan time.Time
    }
    

    Notice that clock's NewTimer returns a Timer from k8s clock package, which is defined as:

    type Timer interface {
        C() <-chan time.Time
        Stop() bool
        Reset(d time.Duration) bool
    }
    

    And that's what you are calling to get the channel.

    This is so they can swap out the timer, likely for test cases.

    So, while it looks like the stdlib's Timer type, it's really an interface to allow swapability.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?