interface理解

发布时间 2023-08-13 22:30:15作者: 意犹未尽

interface(接口)是golang最重要的特性之一,实现多态。Interface类型可以定义一组方法,但是这些不需要实现。并且interface不能包含任何变量。

特点

  • interface 是方法或行为声明的集合
  • interface接口方式实现比较隐性,任何类型的对象实现interface所包含的全部方法,则表明该类型实现了该接口。
  • interface还可以作为一中通用的类型,其他类型变量可以给interface声明的变量赋值。
  • interface 可以作为一种数据类型,实现了该接口的任何对象都可以给对应的接口类型变量赋值。

两种接口

​runtime.iface

package main

import "fmt"

// Person 定义接口
type Person interface {
    GetName() string
    GetAge() uint32
}

// Student 定义类型
type Student struct {
    Name string
    Age uint32
}

func (s Student) GetName()  string{
    return s.Name
}
func (s Student) GetAge()  uint32{
    return s.Age
}

func main() {

var student Student
    student.Age = 12
    student.Name = "小明"

var person Person
    person = student  //接口执行向student
    fmt.Printf("name:%s,age: %d\n", person.GetName(), person.GetAge())
}

​内部结构

runtime.eface​

使用​​runtime.eface​​​表示第二种不包含任何方法的接口,第二种在我们日常开发中经常使用到,所以在实现时使用了特殊的类型。从编译角度来看,golang并不支持泛型编程。但还是可以用​​interface{}​​ 来替换参数,而实现泛型。

 

参考

来源:

https://blog.51cto.com/u_14523732/5639864

https://blog.csdn.net/yuqiang870/article/details/124746693