golang

结构体声明 Link to heading

结构体可以理解为多种类型的集合,是一种自己定义的复杂类型

package main

import "fmt"

type Stduent struct {
	Name    string
	Age     int16
	Score   int16
	Address string
}

func main() {}

结构体使用 Link to heading

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: "上海市松江区"}
}

结构体的方法 Link to heading

一个结构体的专属方法,可以实现面向对象操作

package main

import "fmt"

type Stduent struct {
	Name    string
	Age     int16
	Score   int16
	Address string
}

// 绑定Stduent的指针
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()
}

面向对象继承 Link to heading

一个结构体继承另外一个的属性方法

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()
}