这是我参与「第五届青训营 」伴学笔记创作活动的第 1 天.
GO语言特性
1.高性能、高并发 2.语法简单、学习曲线平缓 3.丰富的标准库 4.完善的工具链 5.静态链接 6.快速编译 7.跨平台 8.垃圾回收 ##基础语法
变量的声明
var a int
var b = true
c := "123"
const d = 998244353
fmt.Println(a, b, c, d)
if else
num := 9
if num&1 == 1 {
fmt.Println("奇数")
} else {
fmt.Println("偶数")
}
if num := 10; num&1 == 1 {
fmt.Println("奇数")
} else {
fmt.Println("偶数")
}
循环
for j := 1; j <= 10; j++ {
fmt.Println(j)
}
switch
a := 1
switch a {
case 1:
fmt.Printf("ok")
case 2:
fmt.Println("no")
default:
fmt.Println("-1")
}
数组和切片
var a [2][3]int
for i := 0; i < 2; i++ {
for j := 0; j < 3; j++ {
a[i][j] = i * j
fmt.Println(a[i][j])
}
}
b := make([]int, 5)
b[4] = 1
fmt.Println(b[:4])
fmt.Println(b[2:])
map
ma := make(map[string]int)
ma["cyl"] = 1
ma["123"] = 2
delete(ma, "123")
fmt.Println(ma)
fmt.Println(ma["cyl"])
fmt.Println(len(ma))
r, ok := ma["c"]
fmt.Println(r, ok)
函数
func add(a int, b int) (int, bool) {
return a + b, true
}
结构体方法
type student struct {
name string
id int
password string
}
func (stu student) cheak(s string) (bool, error) {
return stu.password == s, nil
}
func (stu *student) update(s string) error {
stu.password = s
return nil
}
func main() {
d := student{name: "cyl", id: 9, password: "123456"}
d.update("12345")
a, b := d.cheak("12345")
//if b!=
fmt.Println(a, b)
}
错误处理
a, b := d.cheak("12345")
if b != nil {
fmt.Println(b)
}
字符串格式化
type student struct {
name string
id int
password string
}
func main() {
d := student{name: "cyl", id: 9, password: "123456"}
fmt.Printf("%v\n", d) //{cyl 9 123456}
fmt.Printf("%+v\n", d) //{name:cyl id:9 password:123456}
fmt.Printf("%#v\n", d) //main.student{name:"cyl", id:9, password:"123456"}
}
JSON处理
JSON 指的是 JavaScript 对象表示法(JavaScript Object Notation)
在javaScript中,我们可以直接使用json,因为JavaScript中内置了json的解析,把任何的JavaScript对象变成json,就是把这个对象序列化成一个json格式的字符串,这样才能通过网络传递给其他计算机。如果我们收到json格式的字符串,只需要把它反序列化为一个JavaScript对象,就可以在JavaScript中直接使用这个对象了。
type student struct {
Name string `json:"name"`
Id int `json:"id"`
PassWord string `json:"password"`
}
func main() {
d := student{Name: "cyl", Id: 9, PassWord: "123456"}
buf, err := json.Marshal(d)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(buf)
fmt.Println(string(buf))
buff, err := json.MarshalIndent(d, "", "\t")
if err != nil {
fmt.Println(err)
return
}
fmt.Println(buff)
fmt.Println(string(buff))
}
总结
后面在字节内部课中通过三个简单的小项目学习并掌握Go语言的基础语法,第一个是猜数字游戏,第二个是在线词典,第三个是SOCK5代理.通过这两节课,能够掌握Go的基础语法并且简单应用,而且Go有些语法和C,python类似,也降低了一些上手难度