Golang中的无主体函数

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

Bodiless function in Golang

问题

阅读math/floor.go的源代码,从第13行开始,我看到了以下代码:

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
}

看起来func Floor没有函数体。我尝试将这些代码复制粘贴到我的go文件中,但它无法编译。错误消息是missing function body。所以我的问题是:在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 &lt; 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.

答案1

得分: 18

这是汇编语言中函数实现的方式。你可以在floor_ARCH.s文件中找到汇编实现的代码(例如:AMD64)。根据规范的引用:

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

英文:

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.

答案2

得分: 4

在我的情况下,我遇到了一个错误:"../../../pkg/mod/golang.org/x/tools@v0.0.0-20190814235402-ea4142463bf3/go/ssa/interp/testdata/src/fmt/fmt.go:3:6: missing function body"。

这是因为我在使用fmt时没有导入它,所以我的IDE导入了错误的包。

我通过移除导入语句(golang.org/x/tools/go/ssa/interp/testdata/src/fmt)并导入fmt来解决了这个问题。

英文:

In my case I had "../../../pkg/mod/golang.org/x/tools@v0.0.0-20190814235402-ea4142463bf3/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

huangapple
  • 本文由 发表于 2015年3月27日 01:32:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/29285129.html
匿名

发表评论

匿名网友

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

确定