Go语言基础 Part2

说明

本文为GO语言基础的学习笔记

面对对象

匿名字段

通过匿名字段实现继承操作
同名字段:(父类和子类都有定义的字段称为同名字段)采用就近原则
指针匿名字段: 子类中含父类的指针

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
package main
type person struct {
name string
age int
sex string
}
//结构体嵌套结构体
type Student struct {
//通过匿名字段实现继承操作
person //结构体名称作为结构体成员
id int
score int
}
type Student2 struct {
//通过匿名字段实现继承操作
*person //结构体名称作为结构体成员
id int
score int
}

func main01() {
var stu Student = Student{person{"Alice",19,"Woman"},11,100}
fmt.Println(stu) //student

var stu2 student2 = student1{&person1{"LiLith",15,"Woman"},15,66}
Println(stu2.name)

方法

方法的定义:

1. 为已经存在的数据类型取别名
2. 定义函数
1
2
3
4
5
6
7
8
9
10
11
12
13
//取别名
type Int int
//方法
//func 【方法接受者】 方法名 【参数列表】 返回值类型
func (a Int) add (b Int) Int{
return a+b
}
func main() {
//根据数据类型 绑定方法
var a Int=10
val:=a.add(20)
fmt.Println(val)
}

方法实例

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
42
43
44
45
46
47
package main

type student2 struct {
name string
age int
sex string
cscore int
mscore int
escore int
}
func (s *student2) SayHello() {
fmt.Printf("大家好,我叫%s,我今年%d岁了,我是%s生\n", s.name, s.age, s.sex)
}

//方法名可以和函数名重名
func SayHello(){
fmt.Println("hello world")
}

//方法2 打印成绩
func (s *student2) PrintScore() {
sum := s.cscore + s.escore + s.mscore

fmt.Printf("总成绩为:%d 平均成绩:%d\n", sum, sum/3)
}

//为对象赋值
func (s *student2) InitInfo(name string, age int, sex string, cscore int, mscore int, escore int) {
s.name=name
s.age=age
s.sex=sex
s.mscore=mscore
s.cscore=cscore
s.escore=escore
}


func main() {
//stu := student2{"贾宝玉", 18, "男", 66, 77, 88}
var stu student2
//初始化对象信息
stu.InitInfo("贾宝玉", 18, "男", 66, 77, 88)

SayHello()
//stu.SayHello()
stu.PrintScore()
}