Go中接口的用法 [英] Usage of interface in Go
问题描述
我想用一个简单示例了解它在Go(语言)中的使用.
I would like to understand the interface type with a simple example of it's use in Go (Language).
我阅读了网络文档,但没有理解.
I read the web documentation, but I don't get it.
推荐答案
go接口背后的想法是鸭子输入.简而言之就是:如果您看起来像鸭子,而嘎嘎像鸭子,那么您就是鸭子.这意味着,如果您的对象实现了鸭子的所有功能,那么将其用作鸭子就不会有问题.这是一个示例:
The idea behind go interfaces is duck typing. Which simply translates into: If you look like a duck and quack like a duck then you are a duck. Meaning that if your object implements all duck's features then there should be no problem using it as a duck. Here is an example:
package main
import (
"fmt"
)
type Walker interface {
Walk() string
}
type Human string
type Dog string
func (human Human) Walk() string { //A human is a walker
return "I'm a man and I walked!"
}
func (dog Dog) Walk() string { //A dog is a walker
return "I'm a dog and I walked!"
}
//Make a walker walk
func MakeWalk(w Walker) {
fmt.Println(w.Walk())
}
func main() {
var human Human
var dog Dog
MakeWalk(human)
MakeWalk(dog)
}
此处,Human
是Walker
,Dog
是Walker
.为什么?因为他们俩都很好.Walk
.它们都实现Walk () string
函数.因此,这就是为什么您可以在它们上执行MakeWalk
的原因.
Here a Human
is a Walker
and a Dog
is a Walker
. Why? Because they both.. well... Walk
. They both implement the Walk () string
function. So this is why you can execute MakeWalk
on them.
当您希望不同类型以相同方式运行时,这将非常有用.一个实际的例子是文件类型对象(套接字,文件对象)-您需要对所有这些对象都具有Write和Read函数.然后,您可以独立于其类型使用相同的写入和读取方式-很酷.
This is very helpful when you want different types to behave in the same manner. A practical example would be file type objects (sockets, file objects) - you need a Write and a Read function on all of them. Then you can use Write and Read in the same fashion independent of their type - which is cool.
这篇关于Go中接口的用法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!