接口

1. 定义: Interface类型可以定义一组方法,但是这些不需要实现。并且interface不能包含任何变量。

type example interface{
        Method1(参数列表) 返回值列表
        Method2(参数列表) 返回值列表
}

2.interface类型默认是一个指针

	type example interface{

			Method1(参数列表) 返回值列表
			Method2(参数列表) 返回值列表
			…
	}

	var a example
	a.Method1()

3. 接口实现

  • a. Golang中的接口,不需要显示的实现。只要一个变量,含有接口类型中的所有方法,那么这个变量就实现这个接口。因此,golang中没有implement类似的关键字
  • b. 如果一个变量含有了多个interface类型的方法,那么这个变量就实现了多个接口。
  • c. 如果一个变量只含有了1个interface的方部分方法,那么这个变量没有实现这个接口。
package main

import "fmt"

type Car interface {
    GetName() string
    Run()
    DiDi()
}

type Test interface {
    Hello()
}

type BMW struct {
    Name string
}

func (p *BMW) GetName() string {
    return p.Name
}

func (p *BMW) Run() {
    fmt.Printf("%s is running\n", p.Name)
}

func (p *BMW) DiDi() {
    fmt.Printf("%s is didi\n", p.Name)
}
func (p *BMW) Hello() {
    fmt.Printf("%s is hello\n", p.Name)
}

type BYD struct {
    Name string
}

func (p *BYD) GetName() string {
    return p.Name
}

func (p *BYD) Run() {
    fmt.Printf("%s is running\n", p.Name)
}

func (p *BYD) DiDi() {
    fmt.Printf("%s is didi\n", p.Name)
}

func main() {
    var car Car
    var test Test
    fmt.Println(car)

    // var bwm = BMW{}
    // bwm.Name = "宝马"
    bwm := &BMW{
        Name: "宝马",
    }
    car = bwm
    car.Run()

    test = bwm
    test.Hello()

    byd := &BMW{
        Name: "比亚迪",
    }
    car = byd
    car.Run()
    // var a interface{}
    // var b int
    // var c float32

    // a = b
    // a = c
    // fmt.Printf("type of a %T\n", a)
}
接口实现案例Car

相关文章: