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

输出:

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

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

技术教程推荐

深入浅出gRPC -〔李林锋〕

持续交付36讲 -〔王潇俊〕

软件工程之美 -〔宝玉〕

Flutter核心技术与实战 -〔陈航〕

高并发系统设计40问 -〔唐扬〕

Django快速开发实战 -〔吕召刚〕

Dubbo源码剖析与实战 -〔何辉〕

结构写作力 -〔李忠秋〕

给程序员的写作课 -〔高磊〕

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