package main
import (
"fmt"
)
type Animal struct {
Age int
}
type Person struct {
Animal
Sex int
}
func (animal *Animal) getAge() int {
return animal.Age
}
func (animal *Animal) getName() string {
return "animal"
}
func (person Person) getSexName() string {
return "man"
}
func (person Person) getName() string {
return "person"
}
func main() {
var person Person
person.Age = 20
person.Sex = 1
fmt.Println(person.getAge())
fmt.Println(person.getSexName())
fmt.Println(person.getName())
}
输出
20
man
person
成员变量,是指针类型
package main
import (
"fmt"
)
type Animal struct {
Age int
}
type Person struct {
*Animal
Sex int
}
func (animal *Animal) getAge() int {
return animal.Age
}
func (animal *Animal) getName() string {
return "animal"
}
func (person Person) getSexName() string {
return "man"
}
func (person Person) getName() string {
return "person"
}
func main() {
var person = Person{&Animal{20}, 1}
fmt.Println(person.getAge())
fmt.Println(person.getSexName())
fmt.Println(person.getName())
}