Go中接口的使用 [英] Usage of interface in Go

查看:30
本文介绍了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)
}

这里 HumanWalkerDogWalker.为什么?因为他们都......好吧......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屋!

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