这次我们学习一下golang语言
gitee: go-study
定义
定义的变量或者函数必须用到(pakeage内的全局除外)
var a int // 默认为0
var b string //默认为""
fmt.Printf("%d %q\n",a, s)
复制代码
直接定义可以不写类型(int..)go会自行判断
var a, b = 3, 4
var s = "abc"var a, b, c, s = 3, 4, true, "def"
复制代码
不写var(函数内可用:=,函数外不可以用),
a, b, c, s := 3, 4, true, "def"
b = 5 //第二次不用:=
复制代码
简写var
var aa = 3
var ss = "kkk"
var bb = truevar (aa = 3ss = "kkk"bb = true
)
复制代码
内建变量类型
- bool, string
- (u)int, (u)int8, (u)int16, (u)int32, (u)int64, uintptr
- byte, rune
- float332, float64, complex64, complex128
强制类型转换
var a, b int = 3, 4
var c int
c = math.Sqrt(float64(a*a + b*b))) //报错
c = int(math.Sqrt(float64(a*a + b*b))) //正确
复制代码
常量和枚举
- 常量(不要大写) const数值可以作为各种类型使用
const filename = "abc.txt"
const a, b = 3, 4 //不定义int类型则为文本
var c int
c = int(math.Sqrt(a*a + b*b))
复制代码
- 枚举
const (cpp = 0java = 1pytion = 2golang = 3
)
fmt.Println(cpp, java, pytion, golang) //0,1,2,3
复制代码
- iota
const (cpp = iotajavapytiongolang
)
fmt.Println(cpp, java, pytion, golang)//0,1,2,3const (cpp = iota_ //跳过javapytiongolang
)const (b = 1 << (10 * iota)kbmbgbtbpb
)
fmt.Println(b, kb, mb, gb, tb, pb) //1 1024 1048576 1073741824 1099511627776 1125899906842624
复制代码
条件语句
- if
const filename = "abc.txt"
contents, err := ioutil.ReadFile(filename)
if err != nil {fmt.Println(err)
} else {fmt.Printf("%s\n", contents)
}
// 第二种写法(类似for) contents外部访问不到
const filename = "abc.txt"
if contents, err := ioutil.ReadFile(filename); err != nil {fmt.Println(err)
} else {fmt.Printf("%s\n", contents)
}
fmt.Printf("%s\n", contents) //报错
复制代码
- switch
func grade(score int) string {g := ""switch {case score < 0 || score > 100:panic(fmt.Sprintf("Wrong score: %d", score))case score < 60:g = "f"case score < 80:g = "c"case score < 90:g = "b"case score <= 100:g = "a"}return g
}
fmt.Println(grade(0),grade(59),grade(69),
)// f f c
fmt.Println(grade(0),grade(59),grade(69),grade(101),
)// 报错,其他数值算不出来
复制代码
后续会继续更新