没有函数体的函数是什么意思?

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

What does a function without body mean?

问题

func After(d Duration) <-chan Time {
return NewTimer(d).C
}

func NewTimer(d Duration) *Timer {
c := make(chan Time, 1)
t := &Timer{
C: c,
r: runtimeTimer{
when: nano() + int64(d),
f: sendTime,
arg: c,
},
}
startTimer(&t.r)
return t
}

英文:

I'm reading the code that package time, and then I want to know how the func After(d Duration) &lt;-chan Time works.

I found the code follows:

func After(d Duration) &lt;-chan Time {
    return NewTimer(d).C
}

func NewTimer(d Duration) *Timer {
    c := make(chan Time, 1)
    t := &amp;Timer{
        C: c,
        r: runtimeTimer{
            when: nano() + int64(d),
            f:    sendTime,
            arg:  c,
        },
    }
    startTimer(&amp;t.r)
    return t
}

So I found the definition of startTimer - it's so weird that function startTimer does not have a function body.

func startTimer(*runtimeTimer)

I want to know that :

  1. Where is the real code of startTimer
  2. Why an "abstract method" can exists here
  3. Why the author of Go wrote it like this

Thanks!

答案1

得分: 56

  1. 该函数在这里被定义:

    // startTimer将t添加到计时器堆中。
    //go:linkname startTimer time.startTimer
    func startTimer(t *timer) {
        if raceenabled {
    	       racerelease(unsafe.Pointer(t))
    	   }
    	   addtimer(t)
    }
    
  2. 函数声明

    函数声明可以省略函数体。这样的声明为在Go之外实现的函数提供了签名,比如汇编例程。

  3. 并非每种编程语言都能完全表达自己的运行时(例如C可以)。Go运行时和标准库的一部分是用C编写的,一部分是用汇编语言编写的,而另一部分是用.goc编写的,这是一种未经充分文档化的Go和C混合语言。

英文:
  1. The function is defined here:

    // startTimer adds t to the timer heap.
    //go:linkname startTimer time.startTimer
    func startTimer(t *timer) {
        if raceenabled {
    	       racerelease(unsafe.Pointer(t))
    	   }
    	   addtimer(t)
    }
    
  2. Function declarations:

    > A function declaration may omit the body. Such a declaration provides the signature for a function implemented outside Go, such as an assembly routine.

  3. Not every programming language can express its own runtime entirely (C can, for example). Parts of the Go runtime and the standard library are in C, parts are in assembly while some other are in .goc, which is a not well documented hybrid of Go and C.

huangapple
  • 本文由 发表于 2013年2月18日 22:47:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/14938960.html
匿名

发表评论

匿名网友

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

确定