Go 接口的一些示例是什么? [英] What are some examples of Go interfaces?

查看:35
本文介绍了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.

谁能指出一个在工作程序中使用 Go 接口的简单例子?

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

推荐答案

这是一个正在进行中的学习练习,当然是良好风格的一个糟糕例子,但是 给你(spec).

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

此外,作为一个更奇特的例子,我发布了一个帖子 在关于使用 interface{} 构建处理匿名数据的函数(在本例中为三元运算"函数)的 go-nuts 邮件列表中:

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
", result);
}

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

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