golang接口interface实现多态

interface实现多态

    • 一、代码
    • 二、运行结果

一、代码

package main

import (
	"fmt"
)

//interface
type IPerson interface {
	Info() string
}

//teacher
type Teacher struct {
	Name string
}

func (t *Teacher) Info() string {
	return "teacher name: " + t.Name
}

//student
type Student struct {
	Name string
}

func (s *Student) Info() string {
	return "student name: " + s.Name
}

//output with interface
func PersonInfo(p IPerson) {
	fmt.Println(p.Info())
}

func main() {
	PersonInfo(&Teacher{"Tom"})
	PersonInfo(&Student{"Lucy"})
}

二、运行结果

teacher name: Tom
student name: Lucy

你可能感兴趣的:(golang,golang,interface,多态)