zoukankan      html  css  js  c++  java
  • Go interface 操作示例

    原文链接:Go interface操作示例

    特点:

        1. interface 是一种类型

           interface 是一种具有一组方法的类型,这些方法定义了 interface 的行为。go 允许不带任何方法的 interface ,这种类型的           interface 叫 empty interface

        2. interface 变量存储的是实现者的值

          interface 的重要用途就体现在函数参数中,如果有多种类型实现了某个 interface,这些类型的值都可以直接使用interface 的变量存储。

        3. 空的 interface

           interface{} 是一个空的 interface 类型,根据前文的定义:一个类型如果实现了一个 interface 的所有方法就说该类型实现了这个 interface,空的 interface 没有方法,所以可以认为所有的类型都实现了 interface{}。如果定义一个函数参数是 interface{} 类型,这个函数应该可以接受任何类型作为它的参数

    package main
    
    import "fmt"
    
    type Animal interface {
        Eat(food string)
        Call() string
    }
    
    type Sheep struct {
        food string
    }
    
    // 实现接口方法
    func (sheep *Sheep) Eat(food string) {
        sheep.food = food
    }
    
    // 实现接口方法
    func (sheep Sheep) Call() string {
        fmt.Println("Sheep has eat: ", sheep.food)
        return "mm"
    }
    
    func main() {
        var sheep Animal
    
        // 两种写法一样
        // sheep = new(Sheep)
        sheep = &Sheep{food: ""}
        sheep.Eat("grass")
        sing := sheep.Call()
        fmt.Println("Sheep song: ", sing)
    }

    运行结果如下:

    [root@wangjq test]# go run interface.go 
    Sheep has eat:  grass
    Sheep song:  mm
  • 相关阅读:
    leetcode-剑指19-OK
    leetcode-剑指38-?
    leetcode-剑指36-OK
    leetcode-剑指41-OK
    leetcode-剑指20-OK
    leetcode-剑指16-OK
    nginx重写路由隐藏入口文件报错引发的思考
    Go之并发
    Go之接口
    Go实现学生管理系统
  • 原文地址:https://www.cnblogs.com/wangjq19920210/p/11514751.html
Copyright © 2011-2022 走看看