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

报告相同问题?

悬赏问题

  • ¥15 目详情-五一模拟赛详情页
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line