Skip to content

【1】接口本身不能创建实例,但是可以指向一个实现了该接口的自定义类型的变量。

【2】只要是自定义数据类型,就可以实现接口,不仅仅是结构体类型。

【3】一个自定义类型可以实现多个接口

go
package main

import "fmt"

type AInterface interface{
        a()
}

type BInterface interface{
        b()
}

type Stu struct{

}

func (s Stu) a(){
        fmt.Println("aaaa")
}

func (s Stu) b(){
        fmt.Println("bbbb")
}

func main(){
        var s Stu
        var a AInterface = s
    var b BInterface = s
        a.a()
        b.b()
}

【4】一个接口(比如A接口)可以继承多个别的接口(比如B,C接口),这时如果要实现A接口,也必须将B,C接口的方法也全部实现。

go
package main

import "fmt"

type CInterface interface{
        c()
}

type BInterface interface{
        b()
}

type AInterface interface{
        BInterface
        CInterface
        a()
}

type Stu struct{

}

func (s Stu) a(){
        fmt.Println("a")
}
func (s Stu) b(){
        fmt.Println("b")
}
func (s Stu) c(){
        fmt.Println("c")
}

func main(){
        var s Stu
        var a AInterface = s
        a.a()
        a.b()
        a.c()

}

【5】interface类型默认是一个指针(引用类型),如果没有对interface初始化就使用,那么会输出nil

【6】空接口没有任何方法,所以可以理解为所有类型都实现了空接口,也可以理解为我们可以把任何一个变量赋给空接口。

Java · Golang · Rust