Go语法和接口作为参数来运行 [英] Go Syntax and interface as parameter to function

查看:149
本文介绍了Go语法和接口作为参数来运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Go编程语言的新手,最近遇到以下代码:

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

但是,我不明白函数签名背后的含义。它接受一个接口作为参数。你能解释一下我的工作原理吗?谢谢

解决方案

Go使用接口来泛化类型。所以,如果你想要一个函数接受一个特定的接口
,你可以这样写:

  func MyFunction(t SomeInterface){.. 。

满足 SomeInterface 的每种类型都可以被传递给 MyFunction



现在, SomeInterface can看起来像这样:

  type SomeInterface接口{
SomeFunction()
}
code>

为了满足 SomeInterface ,实现它的类型必须实现 SomeFunction()。如果你需要一个空的接口( interface {} ),那么这个对象不需要$ b(

$ b实现了传递给函数的任何方法:

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

上面的这个函数将把每个类型都看作所有类型实现空接口



取回类型

现在你可以拥有所有可能的类型,问题是如何获得
之前实际放入的类型。空的接口不提供任何方法,因此你
不能调用任何这样的值。

为此你需要输入断言:让运行时检查值Y中是否存在X类型,如果是,则
将其转换为该类型。



示例:

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

在这个例子中,输入参数 t 被声明类型为 SomeConcreteType 。如果 t
实际上是类型 SomeConcreteType v 将保存该类型的实例, ok 将使
为真。否则, ok 将为false。有关详细信息,请参阅规范类型断言


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

解决方案

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.

这篇关于Go语法和接口作为参数来运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆