访问权限
Go语言中函数名的首字母大小写需要特别注意,是用来控制对方法的访问权限的,当方法的首字母为大写时,这个方法对于所有的包都是公开的。其他包可以随意调用,当方法的首字母为小写时,这个方法是私有的,其他包无法访问。
结构体排序
Go语言中sort不保证排序的稳定性(两个相同的值,排序之后相对位置不变),排序的稳定性由sort.Stable()函数来保证,示例:
package main
import (
"fmt"
"sort"
)
type Student struct {
name string
score int
}
type StudentSlice []Student
func (stus StudentSlice) Len() int {
return len(stus)
}
func (stus StudentSlice) Swap(i, j int) {
stus[i], stus[j] = stus[j], stus[i]
}
func (stus StudentSlice) Less(i, j int) bool {
return stus[i].score < stus[j].score
}
func main() {
s := StudentSlice{
{
name: "Lee",
score: 90,
},
{
name: "Bai",
score: 100,
},
{
name: "Hu",
score: 95,
},
}
sort.Stable(s)
fmt.Println(s)
}
输出:
[{Lee 90} {Hu 95} {Bai 100}]
结构体继承
Go语言中是使用组合来实现继承的,例如下面的例子,基于父类,如果创建一个子类,就要把父类给加到子类结构体中,变成其中的一个成员,同时,在子类中也可以覆写父类的方法,例如Study(),如果想要调用父类的方法,应该主动去调用父类的成员来实现。
package main
import "fmt"
type Father struct {
Name string
}
func (fa Father) Work() {
fmt.Println("working")
}
func (fa Father) Study() {
fmt.Println("Studying")
}
type Child struct {
Father
}
func (ch Child) Study() {
fmt.Println("child Studying")
}
func main() {
child := Child{}
child.Work()
child.Study()
child.Father.Study()
}
输出:
working
child Studying
Studying
结构体字段标签
结构体字段标签是指结构体成员字段的额外信息,常用作对字段进行说明,尤其在json序列化以及对象关系映射时,标签信息是静态的!无需实例化结构体,可以通过你反射获取,如果一个字段有多个标签,需要在中间用空格分割,示例:
package main
import (
"fmt"
"reflect"
)
type Student struct {
name string `json:"name" level:"10"`
}
func main() {
stu := Student{}
typeinfo := reflect.TypeOf(stu)
fileName, ok := typeinfo.FieldByName("name")
if ok {
fmt.Println(fileName.Tag.Get("json"), fileName.Tag.Get("level"))
}
}
输出:
name 10