Go - 接口

Go - 接口 首页 / Golang入门教程 / Go - 接口

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

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

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

语法:

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

其中Namer是接口类型。

无涯教程网

Go 接口示例

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)
}

输出:

链接:https://www.learnfk.comhttps://www.learnfk.com/go/go-interface.html

来源:LearnFk无涯教程网

Accelrating...
I am toyota, I accelerate fast...
{suzuki blue}
{Toyota Red 100}

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

赵成的运维体系管理课 -〔赵成〕

Java核心技术面试精讲 -〔杨晓峰〕

iOS开发高手课 -〔戴铭〕

Node.js开发实战 -〔杨浩〕

Netty源码剖析与实战 -〔傅健〕

后端技术面试 38 讲 -〔李智慧〕

SRE实战手册 -〔赵成〕

数据中台实战课 -〔郭忆〕

Serverless入门课 -〔蒲松洋(秦粤)〕

好记忆不如烂笔头。留下您的足迹吧 :)