Golang教程第11篇-接口

1、接口定义

一个类实现了一个接口,那么这个接口就可以指向这个类或者说可以使用这个类给接口赋值

package main

import "fmt"

type Test interface {
    Print()
    Sleep()
}

type People struct {
    name string
    age int
}

type Student struct {
    name string
    age int
    score int
}

func (p *Student) Print() {
    fmt.Println("name:",p.name)
    fmt.Println("age:",p.age)
    fmt.Println("score:",p.score)
}

func (p *Student) Sleep() {
    fmt.Println("student sleep")
}

func (p *People) Print() {
    fmt.Println("name:",p.name)
    fmt.Println("age:",p.age)
}

func (p * People) Sleep() {
    fmt.Println("people sleep")
}

func main() {
    var t Test
    var stu Student = Student{
        name: "stu01",
        age: 20,
        score: 200,
    }
    t = &stu
    t.Print()
    t.Sleep()
    
    var people People = People{
        name: "people",
        age: 200,
    }
    t=&people
    t.Print()
    t.Sleep()   
}

编译执行
07stu02