exported and unexported in Go explanation

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

exported and unexported in Go explanation

问题

我浏览了Golang GitHub仓库中的数学包。其中一些函数有两种不同的声明方式。在下面的代码中,sqrt.goSqrtsqrt函数。我的问题是:
为什么他们要这样实现?有什么好处?这是因为导出和未导出的标识符(小写 vs 大写首字母)吗?

func Sqrt(x float64) float64

// 注意:在某些系统上,Sqrt是用汇编实现的。
// 其他系统有汇编存根,跳转到下面的sqrt函数。
// 在Sqrt是单个指令的系统上,编译器可能会将直接调用转换为直接使用该指令。

func sqrt(x float64) float64 {

math.Sqrt()

英文:

I skimmed through math package in Golang GitHub repo. Some of them have two difference function declarations. In the code below, sqrt.go has Sqrt and sqrt func. My questions are:
Why do they implement it this way? What are the benefits? Is this because of the exported and unexported identifier (lowercase vs uppercase first letter)?

func Sqrt(x float64) float64

// Note: Sqrt is implemented in assembly on some systems.
// Others have assembly stubs that jump to func sqrt below.
// On systems where Sqrt is a single instruction, the compiler
// may turn a direct call into a direct use of that instruction instead.

func sqrt(x float64) float64 {

math.Sqrt()

答案1

得分: 4

根据规范,在你引用的代码的第一行中,没有函数体的函数声明提供了一个在Go之外实现的代码声明,通常是在汇编或其他语言中实现。

在这种情况下,大多数func Sqrt(x float64) float64的实现是在汇编中,例如386amd64arm等。

以下是amd64的示例:

// func Sqrt(x float64) float64
TEXT ·Sqrt(SB),NOSPLIT,$0
    SQRTSD x+0(FP), X0
    MOVSD X0, ret+8(FP)
    RET

对于没有汇编实现的体系结构,汇编代码只是引用了未导出/私有的func sqrt(x float64) float64版本,该版本是用Go编写的。例如mips64体系结构。

TEXT ·Sqrt(SB),NOSPLIT,$0
    JMP ·sqrt(SB)
英文:

According to the spec, function declarations without a body, as you show in the first line of the code you quoted, provide a declaration for code implemented outside of Go; usually in assembly or another language.

In this case, most implementations for that func Sqrt(x float64) float64 are in assembly; for example 386, amd64, arm, etc.

Sample from amd64:

// func Sqrt(x float64) float64
TEXT ·Sqrt(SB),NOSPLIT,$0
	SQRTSD x+0(FP), X0
	MOVSD X0, ret+8(FP)
	RET

For architectures that have no assembly implementation the assembly simply refers to the unexported / private func sqrt(x float64) float64 version that is in Go. For example the mips64 architecture.

TEXT ·Sqrt(SB),NOSPLIT,$0
    JMP ·sqrt(SB)

huangapple
  • 本文由 发表于 2016年4月5日 23:18:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/36430469.html
匿名

发表评论

匿名网友

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

确定