doukekui0914 2014-04-10 22:53
浏览 79
已采纳

静态类型的定义与动态查找

On the book The Go Programming Language Phrasebook said:

If you require performance, then you can use statically typed definitions and avoid the dynamic lookup. If you require flexibility, then you can use the late binding mechanism of interfaces

Can someone explain me what "statically typed definitions" and "dynamic lookup" are for methods and functions in Go?

  • 写回答

2条回答 默认 最新

  • dongxun4110 2014-04-11 01:05
    关注

    Imagine that we have the following code:

    type A struct {}
    
    func (a A) Foo() {
        fmt.Println("Foo called")
    }
    
    type I interface {
        Foo()
    }
    

    I can now create a variable of type A and call this method:

    a := A{}
    a.Foo()
    

    The compiler knows the static type of the variable, so knows that the method call refers to the A.Foo method. So it can compile the above code to use a direct call to A.Foo, which will be as fast as a normal function call.

    If instead we use a variable of type I, things are different:

    var i I = A{}
    i.Foo()
    

    The variable i can hold any type that has a Foo method. In this particular case it is holding an A value, but won't necessarily know this at compile time. So instead the compiler generates code to check the dynamic type of i, look up the associated Foo method and finally call that method. This form of dispatch is slower than the first, but has the benefit the code will work for any type implementing the interface.

    This is similar to C++'s distinction between virtual and non-virtual methods, except rather than the type of dispatch being fixed for a method at its definition, it depends on the type of variable you use in Go.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效