结构体的定义与使用

使用type定义结构体。

1
2
3
4
5
6
7
8
9
10
11
//结构体声明
type structName struct{
property1 int
property2 int
}

//声明结构体变量
var structName substance
structName.property1
structName.property2

例子如下,

1
2
3
4
5
6
7
8
9
10
11
12
13
type person struct{
name string
age int
}

func main() {

var sagume person

sagume.name="sagume"

fmt.Println(sagume.name)
}

类的表示与继承

1
2
3
4
5
6
7
8
9
10
11
12
13
//定义结构体person
type person struct{
name string
age int
}

/*
面向对象的方法定义,
其中 this关键字与java一致,指代当前类。
*/
func (this person) GetName(){
fmt.Println("Name=",person.name)
}

其中,this person 为结构体实例的拷贝,若需修改属性,添加指针。

注意,若类的属性或方法首字母大写,则表示该属性能对外访问,即对于Java中public属性。否则只能对类的内部访问,即对于Java中的private属性。

例子如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
func(this person) show(){
fmt.Println(this.name)
}

func(this *person) setName(newName string){
this.name=newName
}

func main() {

var sagume person

sagume.name="sagume"

sagume.setName("Kishin_Sagume")

sagume.show()
}

在子类结构体中,输入父类结构体,表示继承。

1
2
3
4
5
6
7
8
9
10
11
//父类animal
type animals struct{
weight int
height int
}

//子类sheep
type sheep struct{
animals //表示继承父类animals
...
}

类的多态与接口

Interface本质上为指针,接入该接口的类需要实现该接口定义的方法。

实现例子如下:

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
//接口Animals
type AnimalsIF interface{
sleep()
GetColor() string //类方法获取颜色,返回值为字符串
GetType() string
}

//类Cat
type Cat struct{
color string
Type string
}

//继承接口的类需要实现接口定义的方法
func (this *Cat) GetColor() string{
fmt.Println(this.color)
return this.color
}

func (this *Cat) GetType() string{
fmt.Println(this.Type)
return this.Type
}
/*
var [接口名] [接口] :声明接口

[接口名]=[实现类]{类属性1,类属性2,...}
*/
func main() {
var mimi AnimalsIF
mimi=Cat{"white","cat"}
mimi.GetColor()
mimi.GetType()
}

也可以直接实现接口方法。

1
2
3
4
5
6
7
8
9
func HowtoSleep(animals AnimalsIF){
animals.sleep()
fmt.Println(animals.GetColor(),animals.GetType())
}

func main() {
mimi:=Cat{"white","cat"}
HowtoSleep(&mimi)
}

注意!接口本质上为指针,在实现接口方法时,记得传入变量地址。

总结:

  • 父类(接口)本质上是一个指针
  • 子类继承父类,需要实现父类所有的接口方法
  • 父类指针指向子类的具体数据,调用父类方法即调用对应子类的方法。

空接口与类型断言机制

interface{}为空接口,例如 int, string, float32等皆实现了interface{}这一通用接口。

对通用接口使用”类型断言“,可以查询该接口实现的类型,例子如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
func myFunc(arg interface{}){

fmt.Println("Func is called")
fmt.Println(arg)

//"类型断言":将返回 value 与 ok 两个值,其中value为接口值,ok为布尔值
value,ok:=arg.(string)

if !ok{
fmt.Println("arg is not string")
fmt.Printf("type of value: %T", value)
}else{
fmt.Println("type is string")
}
}

func main() {
myFunc("good")
}