释放双眼,带上耳机,听听看~!
1.强制类型转换
1
2
3
4
5
6
7
8
9
10
11
12
13 1package main
2import (
3 "fmt"
4 "math"
5)
6func main() {
7 var a,b int =3,4
8 var c int
9 //强制类型转换,GO语言没有 隐式类型转换
10 c=int(math.Sqrt(float64(a*a+b*b))) //强制类型 转换
11 fmt.Println(c)
12}
13
2.数组
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24 1package main
2import "fmt"
3func main() {
4 var a[5] int
5 fmt.Println("array a",a)
6
7 a[1]=10
8 a[3]=30
9 fmt.Println("assign:",a)
10 fmt.Println("len:",len(a))
11
12 b:=[5]int{1,2,3,4,5}
13 fmt.Println("init:",b)
14
15 var c[2][3]int
16 for i:=0;i<2;i++ {
17 for j:=0; j<3;j++ {
18 c[i][j]=i+j
19 }
20 }
21 fmt.Println("2d:",c)
22}
23
24
3 结构体 type Person struct
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24 1package main
2import "fmt"
3type Person struct {
4 name string
5 age int
6 email string
7}
8func main() {
9 //初始化
10 person:=Person{"Tom",30,"tom@gmail.com"}
11 fmt.Println(person) //输出(Tom 30 tom@gmail.com)
12
13 var person2=Person{"jan",24,"jan@gmail.com"}
14 fmt.Println(person2)
15
16 pPerson:=&person
17 fmt.Println(pPerson) //输出 &(Tom 30 tom@gmail.com)
18
19 pPerson.age=40
20 person.name="Jerry"
21 fmt.Println(person) //输出{Jerry 40 tom@gmail.com}
22}
23
24
4.结构体 type rect struct
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 1package main
2
3import (
4 "fmt"
5 _ "fmt"
6)
7type rect struct {
8 width,height int
9}
10
11func(r *rect) area() int{ //求面积
12 return r.width*r.height
13}
14func(r *rect) perimeter() int{ //求周长
15 return 2*(r.width+r.height)
16}
17
18func main() {
19 r:=rect{width:10,height:15}
20 fmt.Println("10x15面积:",r.area())
21 fmt.Println("10x15周长:",r.perimeter())
22
23 rp:=&r
24 fmt.Println("10x15面积:",rp.area())
25 fmt.Println("10x15周长:",rp.perimeter())
26}
27
5.创建一个Web服务
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 1package main
2import (
3 "fmt"
4 "net/http"
5)
6
7func myWeb(w http.ResponseWriter, r *http.Request) {
8 fmt.Fprintf(w, "这是一个开始")
9}
10
11func main() {
12 http.HandleFunc("/", myWeb)
13 fmt.Println("服务器即将开启,访问地址 http://localhost:8080")
14
15 err := http.ListenAndServe(":8080", nil)
16 if err != nil {
17 fmt.Println("服务器开启错误: ", err)
18 }
19}
20