MENU

Go 学习笔记:接口

August 24, 2021 • Read: 263 • Golang

与常规的面向对象语言不同,这门语言没有提供类(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()
}
Archives Tip
QR Code for this page
Tipping QR Code