英文:
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 < 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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论