// method project main.go
package main
import (
"fmt"
)
type Human struct {
name string
age int
phone string
}
type Student struct {
Human
school string
}
type Employee struct {
Human
company string
}
func (h *Human) SayHi() {
fmt.Printf("Hi, I am %s you can call me on %s\n", h.name, h.phone)
}
func (e *Employee) SayHi() {
fmt.Printf("Hi, I am %s you can call me on %s, I Work at %s\n", e.Human.name, e.phone, e.company)
}
type Stringer interface {
String() string
}
func (s *Student) String() string {
return fmt.Sprintf("Hi, I am %s, you can call me on %s, I study at %s\n", s.name, s.phone, s.school)
}
func main() {
mark := Student{Human{"Mark", 25, "222-222-YYYY"}, "MIT"}
sam := Employee{Human{"Sam", 45, "111-888-XXXX"}, "Golang Inc"}
mark.SayHi()
sam.SayHi()
fmt.Println("Mark info :", mark.String())
var s Stringer = &mark
fmt.Println(s)
}
输出:
Hi, I am Mark you can call me on 222-222-YYYY
Hi, I am Sam you can call me on 111-888-XXXX, I Work at Golang Inc
Mark info : Hi, I am Mark, you can call me on 222-222-YYYY, I study at MIT
Hi, I am Mark, you can call me on 222-222-YYYY, I study at MIT
有疑问加站长微信联系(非本文作者)