slice:=[]int32{1,2,3}// from go 1.17, convert array length must be less then or equals slice length
arr:=(*[3]int32)(slice)fmt.Printf("%+v\n",arr)fmt.Printf("%T\n",arr)
me:=map[string]string{}fmt.Println(me)m:=map[string]string{"name":"tomyli","address":"beijing",}fmt.Println(m)m3:=make(map[int]int,10)fmt.Println(len(m3))//set
m["address"]="shanghai"//exist
v,ok:=m["address"]// ok is true
v,ok=m["age"]// ok is false
fmt.Println(v,ok)//iterate comma, ok
fork,v:=rangem{fmt.Println(k,v)}// delete
delete(m,"address")
指针
1
2
3
4
5
6
7
a:=1aPtr:=&a//aPtr = aPtr + 1
fmt.Println(a)fmt.Println(aPtr)fmt.Printf("a Ptr type is %T",aPtr)fmt.Println(*aPtr)
packagemaintypePersonstruct{Namestring}func(pPerson)Print()string{return"the person name is "+p.Name}func(p*Person)PrintName()string{return"the person name is "+p.Name}funcmain(){person:=Person{}person.Name="tomyli"fmt.Println(person.Print())fmt.Println(person.PrintName())}
packagemaintypePersonstruct{Namestring}func(pPerson)Print()string{return"the person name is "+p.Name}func(p*Person)Names(){p.Name+="123"}funcmain(){person:=Person{}person.Name="tomyli"fmt.Println(Person.Print(person))aPerson:=person1.NamesaPerson()}
一个以方法的reciver参数作为第一个参数的普通函数
继承
不支持继承,支持复合
匿名类型嵌入
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
typeSstruct{io.Readerstrstring}funcmain(){r:=strings.NewReader("hello, tomy")s:=S{Reader:r,str:"world",}varsl=make([]byte,len("hello, tomy"))s.Reader.Read(sl)s.Read(sl)//here like extends
}
var mi MyInterface = t
t, ok := mi.(T)
fmt.Println(t, ok)
判断接口类型
1
2
3
4
5
6
varaint64=10variinterface{}=av1,ok:=i.(int64)fmt.Printf("v1 type is %T",v1)fmt.Println()fmt.Printf("v1 type is int64? %t",ok)
类型为接口类型时,ok为true, v1为真正的类型
空接口
1
2
3
4
5
6
7
8
variinterface{}// go 1.18
// var i any
fmt.Println(i)i=1fmt.Println(i)i="hello"fmt.Println(i)
错误与异常
错误统一用error代表
异常使用panic()
1
2
3
4
5
6
7
8
err:=errors.New("this is an error")err1:=fmt.Errorf("this is an error %w",err)err2:=fmt.Errorf("this is an error %w",err1)fmt.Println(err)fmt.Println(err1)fmt.Println(err2)fmt.Println(errors.Is(err1,err))fmt.Println(errors.Is(err2,err))
panic
在go运行时触发
通过 panic() 触发
导致程序崩溃
1
2
3
4
5
6
7
8
9
10
11
12
13
packagemainfuncfoo(){fmt.Println("foo start")panic("no no no")fmt.Println("foo end")}funcmain(){fmt.Println("main start")foo()fmt.Println("main end")}
recover
异常恢复
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
packagemainfuncfoo(){deferfunc(){ifr:=recover();r!=nil{fmt.Println("got panic")}}()fmt.Println("foo start")panic("no no no")fmt.Println("foo end")}funcmain(){fmt.Println("main start")foo()fmt.Println("main end")}
varchchanintch1:=make(chanint)bufch:=make(chanint,10)fmt.Printf("%+v, type is %T \n",ch,ch)fmt.Printf("%+v, type is %T \n",ch1,ch1)fmt.Printf("%+v, type is %T \n",bufch,bufch)