与常规的面向对象语言不同,这门语言没有提供类(class)和继承这种东西。相对的,go提供了接口(interface)这种类型来解决这些问题
接口是一组method的集合,做的事情就是定义一个协议,但是你不需要去实现它
这里给出了利用接口编程的样例:
/*
* @Author: NorthCityChen
* @LastEditTime: 2021-08-24 15:19:23
* @Description:
* @Website: https://grimoire.cn
* Copyright (c) NorthCityChen All rights reserved.
*/
package main
import (
"fmt"
)
type Animal interface {
Bark()
}
func (dog Dog) Bark() {
fmt.Println("I am", dog.name, "I can bark!")
}
func (cat Cat) Bark() {
fmt.Println("I am", cat.name, "I can't bark!")
}
type Dog struct {
name string
}
type Cat struct {
name string
}
func main() {
var animal Animal
animal = Dog{"yiqi"}
animal.Bark()
animal = Cat{"Tom"}
animal.Bark()
}
作者:NorthCity1984
出处:https://grimoire.cn/golang/go12.html
版权:本文《Go 学习笔记:接口》版权归作者所有
转载:欢迎转载,但未经作者同意,必须保留此段声明;必须在文章中给出原文连接;否则必究法律责任
出处:https://grimoire.cn/golang/go12.html
版权:本文《Go 学习笔记:接口》版权归作者所有
转载:欢迎转载,但未经作者同意,必须保留此段声明;必须在文章中给出原文连接;否则必究法律责任