Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bodiless function in Golang

Tags:

function

go

Reading the source code of math/floor.go, starting from line 13, I read some code like this:

func Floor(x float64) float64

func floor(x float64) float64 {
    if x == 0 || IsNaN(x) || IsInf(x, 0) {
        return x
    }
    if x < 0 {
        d, fract := Modf(-x)
        if fract != 0.0 {
            d = d + 1
        }
        return -d
    }
    d, _ := Modf(x)
    return d
}

It seems the func Floor has no body. I tried to copy and paste these code in my go file. it doesn't compile. The error message is missing function body. So my question is: is a bodiless function legal in Go's syntax? Thanks.

like image 369
Qian Chen Avatar asked Mar 26 '15 17:03

Qian Chen


2 Answers

It's the way how functions are implemented in assembly. You find the assembly implementation in the floor_ARCH.s (e.g.: AMD64) files.

To quote the spec:

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

like image 95
Stephan Dollberg Avatar answered Oct 30 '22 10:10

Stephan Dollberg


In my case I had "../../../pkg/mod/golang.org/x/[email protected]/go/ssa/interp/testdata/src/fmt/fmt.go:3:6: missing function body" error!

and it was because I used fmt without importing it so my IDE imported the wrong package.

I fixed it by removing the import (golang.org/x/tools/go/ssa/interp/testdata/src/fmt)

and just importing fmt

like image 44
Rabhi salim Avatar answered Oct 30 '22 10:10

Rabhi salim