Go界面的一些例子是什么? [英] What are some examples of Go interfaces?

查看:75
本文介绍了Go界面的一些例子是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现一篇有趣的博文关于Go。



我试图理解接口的概念,但是我发现从博客文章中的代码片段中很难这样做,并且几乎不可能从语言规范



任何人都可以在工作程序中指出一个Go接口的简单例子吗?

解决方案这是一个正在进行的学习练习,当然也是一个很好的样式,但在这里你去

另外,作为一个更奇特的例子,我做了 a href =http://groups.google.com/group/golang-nuts/msg/cca70b4f083bd319 =nofollow noreferrer>一篇文章关于使用interface {}构建可与匿名数据一起工作的函数(在本例中为三元操作函数):

  package main 
导入fmt;
func Tern(exp bool,一个接口{},b interface {})(interface {}){
if exp {return a}
return b
}
func main(){
a:= 7; b:= 1;
result:= Tern(a> b,a,b);
fmt.Printf(%d \\\
,result);
}


I found an interesting blog post about Go.

I am trying to understand the concept of interfaces, but I find it very hard to do so from the code fragment in the blog post, and nearly impossible from the language specification.

Can anyone point out a simple example of Go's interfaces in a working program?

解决方案

It's a work-in-progress learning exercise, and certainly a poor example of good style, but here you go (spec).

Additionally, as a more exotic example, I made a post on the go-nuts mailing list regarding using interface{} for building functions that work with anonymous data (in this case, a "ternary operation" function):

package main
import "fmt";
func Tern(exp bool, a interface{}, b interface{}) (interface{}) {
    if exp { return a }
    return b
}
func main() {
    a := 7; b := 1;
    result := Tern(a > b, a, b);
    fmt.Printf("%d\n", result);
}

这篇关于Go界面的一些例子是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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