双链表
type Student struct { Name string Next* Student Prev* Student }
如果有两个指针分别指向前一个节点和后一个节点,我们叫做双链表
package main
import "fmt"
type Student struct {
Name string
Age int
score float32
left *Student
right *Student
}
func trans(root *Student) {
if root == nil {
return
}
fmt.Println(root)
trans(root.left)
trans(root.right)
}
func main() {
var root *Student = new(Student)
root.Name = "stu01"
root.Age = 18
root.score = 100
var left1 *Student = new(Student)
left1.Name = "stu02"
left1.Age = 18
left1.score = 100
root.left = left1
var right1 *Student = new(Student)
right1.Name = "stu04"
right1.Age = 18
right1.score = 100
root.right = right1
var left2 *Student = new(Student)
left2.Name = "stu03"
left2.Age = 18
left2.score = 100
left1.left = left2
trans(root)
}
进行递归判断输出如下:
PS E:\golang\go_pro\src\safly> go run demo.go
&{stu01 18 100 0xc04203df80 0xc04203dfb0}
&{stu02 18 100 0xc04205a000 <nil>}
&{stu03 18 100 <nil> <nil>}
&{stu04 18 100 <nil> <nil>}
PS E:\golang\go_pro\src\safly>
别名
结构体是用户单独定义的类型,不能和其他类型进行强制转换
package main
import "fmt"
type Student struct {
Name string
}
type Stu Student
type inte int
func main() {
var a inte = 100
var b int = 100
b = int(a)
fmt.Println(a,b)
a = inte(b)
fmt.Println(a,b)
fmt.Println("--------------")
var stu = Student{"safly"}
fmt.Println(stu)
var stu1 = Stu{"sss"}
fmt.Println(stu1)
//强转
stu = Student(stu1)
fmt.Println(stu)
}
输出如下:
PS E:\golang\go_pro\src\safly> go run demo.go
100 100
100 100
--------------
{safly}
{sss}
{sss}
PS E:\golang\go_pro\src\safly>
工厂模式
olang中的struct没有构造函数,一般可以使用工厂模式来解决这个问题
make 用来创建map、slice、channel
new用来创建值类型
package main
import "fmt"
type student struct {
Name string
Age int
}
func main() {
// S := new (student)
var stu1 *student = NewStudent("tony", 20)
fmt.Println(*stu1)
stu2 := NewStudent("tony", 200)
fmt.Println(*stu2)
var stu3 = NewStudent("tony", 2990)
fmt.Println(*stu3)
}
/*构造函数*/
func NewStudent(name string,age int) *student {
return &student{
Name:name,Age:age,}
}
输出如下:
PS E:\golang\go_pro\src\safly> go run demo.go
{tony 20}
{tony 200}
{tony 2990}
PS E:\golang\go_pro\src\safly>