李斯特 发表于 2018-9-20 07:16:47

Golang OOP、继承、组合、接口

package main  
import
"fmt"  
func main(){
var h Human  s :
= Student{Grade: 1, Major: "English", Human: Human{Name: "Jason", Age: 12, Being: Being{IsLive: true}}}  fmt.Println(
"student:", s)  fmt.Println(
"student:", s.Name, ", isLive:", s.IsLive, ", age:", s.Age, ", grade:", s.Grade, ", major:", s.Major)//h = s // cannot use s (type Student) as type Human in assignment  
    fmt.Println(h)
  //Heal(s) // cannot use s (type Student) as type Being in argument to Heal
  Heal(s.Human.Being) // true
  

  s.Drink()
  s.Eat()
  
}
  
type Car struct {
  Color string
  SeatCount int
  
}
  
type Being struct {
  IsLive bool
  
}
  
type Human struct {
  Being
  Name string
  Age int
  
}
  
func (h Human) Eat(){
  fmt.Println("human eating...")
  h.Drink()
  
}
  
func (h Human) Drink(){
  fmt.Println("human drinking...")
  
}
  
func (h Human) Move(){
  fmt.Println("human moving...")
  
}
  
type Student struct {
  Human
  Grade int
  Major string
  
}
  
func (s Student) Drink(){
  fmt.Println("student drinking...")
  
}
  
type Teacher struct {
  Human
  School string
  Major string
  Grade int
  Salary int
  
}
  
func (s Teacher) Drink(){
  fmt.Println("teacher drinking...")
  
}
  
type IEat interface {
  Eat()
  
}
  
type IMove interface {
  Move()
  
}

  
type>  Drink()
  
}
  
func Heal(b Being){
  fmt.Println(b.IsLive)
  
}


页: [1]
查看完整版本: Golang OOP、继承、组合、接口