duanmu6231
2016-04-05 15:18
浏览 142
已采纳

Go中导出和未导出的说明

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()

图片转代码服务由CSDN问答提供 功能建议

我在Golang GitHub存储库中浏览了数学包。 其中一些具有两个不同的函数声明。 在下面的代码中, sqrt.go 具有 Sqrt sqrt 功能。 我的问题是: 他们为什么以这种方式实施? 有什么好处? 这是由于导出和未导出的标识符(小写还是大写首字母)引起的吗?

  func Sqrt(x float64)float64 
 
 //注意:Sqrt是在某些系统上的汇编中实现的。
 //其他的汇编存根会跳转到func。  
 //在Sqrt是单个指令的系统上,编译器
 //可能会将直接调用转换为直接使用该指令。
 
func sqrt(x float64)float64 {
 <  /code>

math.Sqrt()

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • doushi1510 2016-04-05 15:49
    已采纳

    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)
    
    点赞 打赏 评论

相关推荐 更多相似问题