GO 语言学习笔记2018-08-31
1 写一个常量的应用:
package main
import (
"fmt"
"math"
)
func consts() {
const (
filename = "abc .txt"
a, b = 3, 4 // go语言中常量设置一般用小写
)
var c int
c = int(math.Sqrt(a*a + b*b))
fmt.Println(filename, c)
}
func main() {
consts()
}
2 枚举iota(自增值种子) 用法:
package main
import "fmt"
func enums() {
const (
cpp = iota
_ //在这里iota加1变成1
javascript
python
c
)
fmt.Println(cpp, javascript, python, c)
}
func main() {
enums()
}
输出结果为:0 2 3 4
3 if语句
package main
import (
"fmt"
"io/ioutil"//引入文件要用的包
)
func main() {
const filename = "abc.txt"
contents, err := ioutil.ReadFile(filename)//调用包“读写文件”
if err != nil {
fmt.Println(err)
} else {
fmt.Printf("%s/n", contents)
}
}
4
package main
import "fmt"
func grade(score int) string {
g := ""
switch {
case score < 0 || score > 100:
panic(fmt.Sprintf(" Wrong score: %d", score)) //输入为非正常分数时报错,一旦发现前面的数据不对,立马停止程序报错。
case score <= 70:
g = "C"
case score < 90 && score > 70:
g = "B"
case score <= 100:
g = "A"
}
return g
}
func main() {
fmt.Println(
grade(56),
grade(77),
grade(99),
)
}
输出结果为:C B A