接口的定义

type TestInterface interface {
    Test()
    Test2()
}

其中,TestInterface为接口名,里面的Test()Test2()分别为定义的方法。

空接口

空接口就是不包含任何方法的接口,所有的类型都可以实现空接口,因此空接口可以实现存储任意类型的数据, 谁实现它就被看作是谁的实现类。其中的T等同于Java中的泛型

package main

import "fmt"

func main() {
    TestFunc(1)       // 使用int类型作为参数传入到函数
    TestFunc("hello") // 使用string类型作为参数传入到函数
    TestFunc(true)    // 使用bool类型作为参数传入到函数
}

// 空接口
type T interface {
}

// 定义一个函数,接收TestFunc接口类型的数据
func TestFunc(t T) {
    fmt.Println(t)
}

可以将空接口类型写为interface{},这种类型可以理解为任何类型。类似其他语言中的object

空接口的使用

空接口既然可以传任意类型,利用这个特性可以把空接口interface{}当做容器使用。

package main

import "fmt"

// 字典结构
type Dict struct {
    data map[string]interface{} // 字典数据
}

// 获取值
func (d *Dict) Get(key string) interface{} {
    return d.data[key]
}

// 设置值
func (d *Dict) Set(key string, value interface{}) {
    d.data[key] = value
}

// 创建一个字典
func NewDict() *Dict {
    return &Dict{make(map[string]interface{})}
}

func main() {
    // 创建一个字典
    dict := NewDict()

    // 设置值
    dict.Set("name", "小王子")
    dict.Set("age", 18)

    // 获取值
    name := dict.Get("name")
    age := dict.Get("age")

    // 输出
    fmt.Println(name, age)
}
Last modification:November 18, 2022
If you think my article is useful to you, please feel free to appreciate