What does a function without body mean?
Asked Answered
B

1

51

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

I found the code follows:

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
}

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!

Brokerage answered 18/2, 2013 at 14:47 Comment(0)
P
58
  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.

Pena answered 18/2, 2013 at 15:2 Comment(2)
@CheneyEah, see this thread for more info on .goc files.Stickybeak
Side note: as with Go, there are bits of the C runtime that are best written in some other language (usually assembly). It may be possible to write, e.g., ldexp and frexp in (non-portable) C but it's usually easier to get it right in assembly.Explanatory

© 2022 - 2024 — McMap. All rights reserved.