golang学习笔记——面向对象(方法)
继承 匿名字段(可以是任意类型)
package main
import (
"fmt"
)
type Person struct {
id int
username string
sex byte
}
type Student struct {
Person //匿名字段继承了Person的成员
score int
rank int
}
func main() {
//顺序初始化
var s1 Student = Student{Person{1, "mayuan", 'm'}, 30, 50}
fmt.Printf("s1 = %+v \n", s1)
//指定初始化
s2 := Student{Person: Person{id: 10}, score: 30}
fmt.Println("s2 = ", s2)
}
-
成员操作(.)
package main
import (
"fmt"
)
type Person struct {
id int
username string
sex byte
}
type Student struct {
Person
score int
rank int
}
func main() {
//顺序初始化
var s1 Student = Student{Person{1, "mayuan", 'm'}, 30, 50}
fmt.Printf("s1 = %+v \n", s1)
//指定元素赋值
s1.username = "cjp"
fmt.Printf("s1 = %+v \n", s1)
//给匿名属性整体赋值
s1.Person = Person{12, "cuijiapeng", 'w'}
//匿名字段中的成员赋值
s1.Person.username = "Bob";
fmt.Printf("s1 = %+v \n", s1)
}
-
指针类型
package main
import (
"fmt"
)
type Person struct {
id int
username string
sex byte
}
type Student struct {
*Person
score int
rank int
}
func main() {
//初始化赋值
s1 := Student{&Person{22, "Join", 'm'}, 23, 2}
fmt.Println("s1 = ", s1)
//先初始化
var s2 Student
p := new(Person)
p.id = 3
p.username = "yunhan"
p.sex = 'm'
s2.Person = p
s2.score = 249
s2.rank = 1
fmt.Println("s2 = ", s2)
}
方法
func(receiver ReceiverType) funcName(parameters)(results)
其中 ReceiverType 本身不能为指针类型
// ReceiverType 本身不能是指针类型
type longs *int
func (tmp longs) test() {}
//但是可以接受指针类型的数据
type longs int
func (tmp *longs) test() {}
package main
import (
"fmt"
)
//面向过程
func Add01(a, b int) int {
return a + b
}
//面向对象写法 方法(为某一类型绑定方法)
type long int
func (tmp long) Add02(num long) long {
return tmp + num
}
func main() {
//面向过程
a := 10
b := 20
fmt.Println("result = ", Add01(a, b))
//面向对象
var tmp long
tmp = 10
fmt.Println("r = ", tmp.Add02(30))
}
-
在调用方法时系统会自动将变量转为 指针或者普通变量
package main
import (
"fmt"
)
type Person struct {
name string
age int
}
func (tmp Person) ShowHello() {
fmt.Println("showHello")
}
func (tmp *Person) ShowWorld() {
fmt.Println("showWorld")
}
func main() {
var p Person = Person{"Bon", 32}
//两个方法都可以调用,自动自动识别转化是值还是指针
p.ShowHello()
p.ShowWorld()
}
-
匿名字段的方法可以被继承
package main
import (
"fmt"
)
type Person struct {
name string
age int
}
type Student struct {
Person
score int
}
func (per Person) Show() {
fmt.Println("Person show")
}
func (stu Student) Msg() {
fmt.Println("Student msg")
}
func main() {
var s Student
s.Person.name = "Bob"
s.Person.age = 10
s.Show()
}
//*********输出***********
Person show
-
方法值和方法表达式 【***方法可以转换成普通函数使用,默认第一个参数为方法的接收值】
package main
import (
"fmt"
)
type Person struct {
name string
age int
}
func (per Person) Show() {
fmt.Println("Person show:", per.name)
}
func main() {
//方法值
p := Person{"Join", 18}
f1 := p.Show
p.name = "Bob"
f1() //输出 Join 如果 func (per Person) Show() 改为 func (per *Person) Show() 将会输出Bob
//方法表达式
f2 := (Person).Show
f2(p)
}