结构体声明
结构体可以理解为多种类型的集合,是一种自己定义的复杂类型
1 2 3 4 5 6 7 8 9 10 11 12
| package main
import "fmt"
type Stduent struct { Name string Age int16 Score int16 Address string }
func main() {}
|
结构体使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| package main
import "fmt"
type Stduent struct { Name string Age int16 Score int16 Address string }
func main() { var norman Stduent norman.Name = "norman" norman.Age = 34 norman.Score = 99 wangyu := Stduent{Name: "wangyu", Age: 23, Score: 89, Address: "上海市松江区"} }
|
结构体的方法
一个结构体的专属方法,可以实现面向对象操作
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
| package main
import "fmt"
type Stduent struct { Name string Age int16 Score int16 Address string }
func (e *Stduent) Show() { fmt.Println("Name = ", e.Name) fmt.Println("Age = ", e.Age) fmt.Println("Score = ", e.Score) fmt.Println("Address = ", e.Address) }
func (e *Stduent) SetName(name string) { e.Name = name }
func (e *Stduent) SeAge(age int16) { e.Age = age }
func (e *Stduent) SetScore(score int16) { e.Score = score }
func (e *Stduent) SetAddress(address string) { e.Address = address }
func main() { a := Stduent{Name: "wangyu", Age: 23, Score: 89, Address: "上海市松江区"} a.Show() a.Score = 100 a.Show() }
|
面向对象继承
一个结构体继承另外一个的属性方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
| package main
import "fmt"
type Human struct { Name string Sex string Age int16 }
func (e *Human) Eat() { fmt.Println("Human eat ...") }
func (e *Human) Walk() { fmt.Println("Human walk ...") }
type SuperMan struct { Human Level int16 }
func (e *SuperMan) Fly() { fmt.Println("SuperMan fly ...") }
func (e *SuperMan) Eat() { fmt.Println("SuperMan eat ...") }
func main() { yu := SuperMan{Human{Name: "yu", Age: 34, Sex: "man"}, 44} yu.Eat() yu.Fly() yu.Walk() }
|