变量定义
func main() {
var a string = "a"
var b = 18
var c, d, e int = 1, 2, 3
var f, g, h = 4, "5", true
i := 6
var (
j = 7
k = 8
l = 9
)
fmt.Println(a, b, c, d, e, f, g, h, i, j, k, l)
}
内建变量类型
- bool string
- int int8 int16 int32 int64 uintptr(没有long)
- byte rune(rune字符 类似char)
- float32 float64 complex64 complex128(复数)
常量和枚举
const name = "go"
func enums() {
const (
cpp = 0
java = 1
python = 2
)
const(
cpp = iota
_
python
js
)
}
条件语句
func main() {
const filename = "abc.txt"
contents, err := ioutil.ReadFile(filename)
if err != nil {
fmt.Println(err)
} else {
fmt.Printf("%s\n", contents)
}
if contents, err := ioutil.ReadFile(filename); err !=nil{
fmt.Printf("%s\n", contents)
}
}
func grade(score int) string {
g := ""
switch {
case score < 0:
panic("no no no")
case score < 60:
g = "C"
case score < 80:
g = "B"
case score <= 100:
g = "A"
case score > 100:
panic("nonono")
}
return g
}
循环
sum := 0
for i := 0; i < 100; i++ {
sum += i
}
fmt.Println(sum)
func convertToBin(num int) string {
result := ""
for ; num > 0; num /= 2 {
lsb := num % 2
result = strconv.Itoa(lsb) + result
}
return result
}
for{
fmt.println("loop")
}