这是我参与「第五届青训营 」伴学笔记创作活动的第 2 天
Go-Day02
1.复习走进Go语言基础语言的课程
- 复习Go的语言的八大特点
- 复习Go的应用场景
- 复习Go的第一个案列HelloWorld的编写
- 复习在Go中如何定义变量
2.继续学习Go语言基础语言课程剩下的部分
- Go中使用if else,不需要加()
package main
import "fmt"
func main() {
if 7%2 == 0 {
fmt.Println("7 is even")
} else {
fmt.Println("7 is odd")
}
if 8%4 == 0 {
fmt.Println("8 is divisible by 4")
}
if num := 9; num < 0 {
fmt.Println(num, "is negative")
} else if num < 10 {
fmt.Println(num, "has 1 digit")
} else {
fmt.Println(num, "has multiple digits")
}
}
- Go中使用循环,只存在for这一种循环语句
package main
import "fmt"
func main() {
i := 1
for {
fmt.Println("loop")
break
}
for j := 7; j < 9; j++ {
fmt.Println(j)
}
for n := 0; n < 5; n++ {
if n%2 == 0 {
continue
}
fmt.Println(n)
}
for i <= 3 {
fmt.Println(i)
i = i + 1
}
}
- Go中switch语句,不需要加break,Go中case不存在穿透性这点跟Java不一样!支持任意类型
package main
import (
"fmt"
"time"
)
func main() {
a := 2
switch a {
case 1:
fmt.Println("one")
case 2:
fmt.Println("two")
case 3:
fmt.Println("three")
case 4, 5:
fmt.Println("four or five")
default:
fmt.Println("other")
}
t := time.Now()
switch {
case t.Hour() < 12:
fmt.Println("It's before noon")
default:
fmt.Println("It's after noon")
}
}
- Go中使用数组,真实开发场景很少使用数组,因为他的长度固定,使用Go中的切片进行替代
package main
import "fmt"
func main() {
var a [5]int
a[4] = 100
fmt.Println("get:", a[2])
fmt.Println("len:", len(a))
b := [5]int{1, 2, 3, 4, 5}
fmt.Println(b)
var twoD [2][3]int
for i := 0; i < 2; i++ {
for j := 0; j < 3; j++ {
twoD[i][j] = i + j
}
}
fmt.Println("2d: ", twoD)
}
- Go中使用切片,使用make创建切片,使用跟数组一样,可以使用copy()拷贝A切片到B切片
package main
import "fmt"
func main() {
s := make([]string, 3)
s[0] = "a"
s[1] = "b"
s[2] = "c"
fmt.Println("get:", s[2]) // c
fmt.Println("len:", len(s)) // 3
s = append(s, "d")
s = append(s, "e", "f")
fmt.Println(s) // [a b c d e f]
c := make([]string, len(s))
copy(c, s)
fmt.Println(c) // [a b c d e f]
fmt.Println(s[2:5]) // [c d e]
fmt.Println(s[:5]) // [a b c d e]
fmt.Println(s[2:]) // [c d e f]
good := []string{"g", "o", "o", "d"}
fmt.Println(good) // [g o o d]
}
总结
1.通过今天对Go语言的基础知识复习,让我对Go语言有了更深的理解,让我有信心学好这门语言,并将这门语言运用到实际开发中;
2.今天学习了Go语言的if else的用法并使用if else完成了基本的逻辑判断;
3.学习了Go语言中for循环,并通过前置知识了解了Go语言中只存在for一种循环,不像Java拥有多种循环语句;
4.学习了switch语句,通过switch可以简化if else的逻辑判断语句并且让语句更加清晰,go中的switch语句的case不存在穿透性,符合条件则会自动执行并跳出;
5.学习了Go中数组的用法,学习了基本的定义数组和使用for循环数组中的元素;
6.学习了比数组更常用的切片,使用make创建切片,使用copy()方法可以拷贝一个切片到另一个切片。