1、struct说明
package main
import (
"fmt"
"time"
)
//struct定义不能包含自身
type Employee struct {
ID int //大写的首字母,对外可见
Name, Address string //相同类型可以放一行
DoB time.Time
Position string
Salary int
ManagerID int
sex string //小写的首字母,对外不可见
//e Employee 错误不能包含自身
e *Employee //可以包含自身的指针
}
func main() {
var dilbert Employee //初始化一个空的struct
fmt.Printf("%+v
", dilbert)
dilbert.Salary -= 5000
fmt.Printf("%+v
", dilbert)
position := &dilbert.Position
*position = "Senior" + *position
fmt.Printf("%+v
", dilbert)
dilbert.sex = "23" //包内可见
fmt.Printf("%+v
", dilbert)
}
2、使用struct实现二叉树
package main
import "fmt"
//二叉树定义
type tree struct {
value int
left, right *tree
}
//堆排
func Sort(values []int) {
var root *tree
for _, v := range values {
root = add(root, v)
}
appendValues(values[:0], root)
}
func appendValues(values []int, t *tree) []int {
if t != nil {
values = appendValues(values, t.left)
values = append(values, t.value)
values = appendValues(values, t.right)
}
return values
}
func add(t *tree, value int) *tree {
if t == nil {
t = new(tree)
t.value = value
return t
}
if value < t.value {
t.left = add(t.left, value)
} else {
t.right = add(t.right, value)
}
return t
}
func main() {
sli := []int{4, 7, 10, 8, 3, 0, -4, 30}
Sort(sli)
fmt.Println(sli)
}
3、使用struct模拟集合set
seen := make(map[string]struct{}) // struct{}大小为0的结构体