英文:
Function signature with no function body
问题
当查看math.Ceil
方法的源代码时,我发现了这样的语法,其中有一个没有函数体的导出函数签名,以及一个包含实现的非导出版本的相同签名:
// Ceil返回大于或等于x的最小整数值。
//
// 特殊情况包括:
// Ceil(±0) = ±0
// Ceil(±Inf) = ±Inf
// Ceil(NaN) = NaN
func Ceil(x float64) float64
func ceil(x float64) float64 {
return -Floor(-x)
}
我猜这是一种允许您轻松导出本地函数的语法。这正确吗?为什么不只是有一个导出函数并在包内使用它呢?
英文:
When viewing the source for the math.Ceil
method, I found this syntax where there's an exported function signature with no body, and a non-exported version of the same signature that includes the implementation:
// Ceil returns the least integer value greater than or equal to x.
//
// Special cases are:
// Ceil(±0) = ±0
// Ceil(±Inf) = ±Inf
// Ceil(NaN) = NaN
func Ceil(x float64) float64
func ceil(x float64) float64 {
return -Floor(-x)
}
I assume this is some syntax which allows you to easily export a local function. Is that correct? And why would one do this instead of just having a single exported function and using it within the package?
答案1
得分: 22
根据Go语言规范。
> 函数声明可以省略函数体。这样的声明为在Go之外实现的函数提供了签名,比如汇编例程。
在这种情况下,Ceil
函数是由特定架构的汇编文件实现的,386架构的实现在floor_386.s
中。amd64和arm架构也各自有一个汇编文件来实现Ceil()
,但这些汇编文件只是调用未导出的ceil()
函数的粘合剂。
英文:
According to the Go language specification.
> A function declaration may omit the body. Such a declaration provides the signature for a function implemented outside Go, such as an assembly routine.
In this case, the Ceil
function is implemented by an architecture specific assembly file for 386 in floor_386.s
. Both the amd64 and arm architectures each have an assembly file that implements Ceil()
as well, but those assembly files are just glue to call the unexported ceil()
function.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论