douke1905 2013-12-01 16:48
浏览 63
已采纳

语法和接口作为参数起作用

I am new to Go programming language and recently encountered the following code:

func (rec *ContactRecord) Less(other interface{}) bool {
  return rec.sortKey.Less(other.(*ContactRecord).sortKey);
}

However, I do not understand the meaning behind the function signature. It accepts an interface as a parameter. Could you please explain me how this works ? Thanks

  • 写回答

2条回答 默认 最新

  • douwei7471 2013-12-01 17:38
    关注

    Go uses interfaces for generalization of types. So if you want a function that takes a specific interface you write

    func MyFunction(t SomeInterface) {...}
    

    Every type that satisfies SomeInterface can be passed to MyFunction.

    Now, SomeInterface can look like this:

    type SomeInterface interface {
        SomeFunction()
    }
    

    To satisfy SomeInterface, the type implementing it must implement SomeFunction().

    If you, however, require an empty interface (interface{}) the object does not need to implement any method to be passed to the function:

    func MyFunction(t interface{}) { ... }
    

    This function above will take every type as all types implement the empty interface.

    Getting the type back

    Now that you can have every possible type, the question is how to get the type back that was actually put in before. The empty interface does not provide any methods, thus you can't call anything on such a value.

    For this you need type assertions: let the runtime check whether there is type X in value Y and convert it to that type if so.

    Example:

    func MyFunction(t interface{}) {
        v, ok := t.(SomeConcreteType)
        // ...
    }
    

    In this example the input parameter t is asserted to be of type SomeConcreteType. If t is in fact of type SomeConcreteType, v will hold the instance of that type and ok will be true. Otherwise, ok will be false. See the spec on type assertions for details.

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

报告相同问题?

悬赏问题

  • ¥15 从Freecad中宏下载的DesignSPHysics,出现如下问题是什么原因导致的(语言-python)
  • ¥30 notepad++ 自定义代码补全提示
  • ¥15 MATLAB有限差分法解一维边值问题
  • ¥200 内网渗透测试 横向渗透 Windows漏洞 Windows权限维持
  • ¥15 数据结构图的相关代码实现
  • ¥15 python中aiohttp.client_exceptions.ContentTypeError
  • ¥30 DeepLung肺结节检测生成最大froc值对应的epoch报错
  • ¥15 信号发生器如何将频率调大,步尽值改成10
  • ¥15 keil 5 编程智能家具,风扇台灯开关,人体感应等
  • ¥100 找一名渗透方面的专家