个性化阅读
专注于IT技术分析

Go使用接口

点击下载

Go具有不同的方法来实现面向对象的概念。 Go没有类和继承。通过其强大的界面来满足这些要求。

接口提供对象的行为:如果可以做到这一点, 则可以在这里使用它。

接口定义了一组抽象方法, 并且不包含任何变量。

句法:

type Namer interface {
			 Method1(param_list) return_type
			 Method2(param_list) return_type
			 ...
}

其中Namer是接口类型。

通常, 接口名称由方法名称加上后缀[e] r组成, 例如打印机, 读取器, 写入器, 记录器, 转换器等。

  • 类型不必明确声明它实现了一个接口:接口是隐式满足的。多种类型可以实现相同的接口。
  • 实现接口的类型也可以具有其他功能。
  • 一个类型可以实现许多接口。
  • 接口类型可以包含对实现接口的任何类型的实例的引用

转到界面示例

package main
import (
   "fmt"
)
type vehicle interface {
   accelerate()
}
func foo(v vehicle)  {
   fmt.Println(v)
   
}
type car struct {
   model string
   color string
}
func (c car) accelerate()  {
   fmt.Println("Accelrating?")
   
}
type toyota struct {
  model string
   color string
   speed int
}
func (t toyota) accelerate(){
   fmt.Println("I am toyota, I accelerate fast?")
}
func main() {
   c1 := car{"suzuki", "blue"}
   t1:= toyota{"Toyota", "Red", 100}
   c1.accelerate()
   t1.accelerate()
   foo(c1)
   foo(t1)
}

输出:

Accelrating...
I am toyota, I accelerate fast...
{suzuki blue}
{Toyota Red 100}
赞(0)
未经允许不得转载:srcmini » Go使用接口

评论 抢沙发

评论前必须登录!