# 基本语法
# 1. 变量
| |
| var a int |
| var b string |
| var c []float |
| var d struct{ |
| x int |
| } |
| |
| var e func() bool |
| |
| var ( |
| f int |
| g string |
| ) |
| |
| |
| var a = 100 |
| a := 100 |
| a, b = 100, "ok" |
| c := 0.17 |
| |
| a, b = b, a |
| _, c = 0, 100 |
# 2. 原生数据类型
| int8 int16 int32 int64 |
| uint8 uint16 uint32 uint64 |
| |
| var a uint16 = math.MaxUint8 + 1 |
| var b = uint8(a) |
| |
| f := "golang编程" |
| len(f) |
| utf8.RuneCountInString(f) |
# 3. 指针
go 语言相比较 C/C++ 限制了指针的偏移和运算能力,仅包含了以下三个概念
| str := "Golang is Good!" |
| strPrt := &str |
| newStr := *strPrt |
| *strPrt = "PHP is Good too!" |
| |
| str := new(string) |
| *str = "Golang is Good!" |
# 4. 使用 flag 从命令行中读取参数
| package main |
| |
| import ( |
| "flag" |
| "fmt" |
| ) |
| |
| func main() { |
| surname := flag.String("surname", "王", "您的姓") |
| var personalName string |
| flag.StringVar(&personalName, "personalName", "小二", "您的名") |
| id := flag.Int("id", 0, "您的ID") |
| flag.Parse() |
| fmt.Printf("I am %v %v, and my id is %v\n", *surname, personalName, *id) |
| } |
| go run Flag.go -surname="杜" -personalName="小猫" -id=100 |
| |
# 5. 常量与类型别名
| |
| const str string = "Golang is Good!" |
| const name = "Golang is Good!" |
| const ( |
| surname = "王" |
| personalName = "小二" |
| ) |
| |
| |
| type aliasInt = int |
| type myInt int |
# 6. 分支与循环控制
| |
| if expression1 { |
| branch1 |
| } else if expression2 { |
| branch2 |
| } else { |
| branch3 |
| } |
| |
| |
| name := "小红" |
| switch name { |
| case "小红": |
| fmt.Println("倒垃圾") |
| case "小明": |
| fallthrough |
| case "小刚": |
| fmt.Println("扫地") |
| default: |
| fmt.Println('没人干活') |
| } |
| |
| |
| score := 90 |
| switch { |
| case score < 100 && score >= 90: |
| fmt.Println("优秀") |
| case score < 90 && score >= 80: |
| fmt.Println("良好") |
| case score < 80 && score >= 60: |
| fmt.Println("及格") |
| case score < 60: |
| fmt.Println("不及格") |
| default: |
| fmt.Println("分数有问题") |
| } |
| |
| |
| for init;condition;end { |
| |
| |
| |
| } |