```
if contents,err:=ioutil.ReadFile("abc.txt");err == nil{
fmt.Print(string(contents))
}else {
fmt.Println("connot print file contents:",err)
}
```
if的条件里可以赋值
if的条件里赋值的变量作用域就在这个if语句里
```
func file(filename string) {
if contents,err:=ioutil.ReadFile(filename);err == nil{
fmt.Print(string(contents))
}else {
fmt.Println("connot print file contents:",err)
}
}
func op(a, b int, op string) int {
var res int
switch op {
case "+":
res=a+b
case "-":
res=a-b
default:
panic("unsupported operator"+op)
}
return res
}
func s( num int) string{
g := ""
switch {
case num>100:
g="F";
case num<=100:
g="E"
default:
g="A"
}
return g
}
```
一个main函数了解条件与循环
```
package main
import (
"fmt"
"io/ioutil"
)
func grade(score int) string {
g := ""
switch {
case score < 0 || score > 100:
// panic("wrong score", score)
case score < 60:
g = "F"
case score < 80:
g = "C"
case score < 90:
g = "B"
case score <= 100:
g = "A"
}
return g
}
func readFile(filename string) string {
contents, err := ioutil.ReadFile(filename)
if err != nil {
panic(err)
}
// else {
// fmt.Printf("%s\n", contents)
// }
return string(contents)
// // if的条件里可以赋值,其赋值的变量作用域就在if的block中
// if contents, err := ioutil.ReadFile(filename); err != nil {
// fmt.Println(err)
// } else {
// fmt.Printf("%s\n", contents)
// }
}
func forcs(cs int) {
for i := 0; i < cs; i++ {
fmt.Printf("i 的值为: %d\n", i)
}
}
func xiao() {
var b int = 5
var a int
for a < b {
a++
fmt.Printf("a 的值为: %d\n", a)
}
}
func ranges() {
numbers := [6]int{1, 2, 3, 5}
for i, x := range numbers {
fmt.Printf("第 %d 位 x 的值 = %d\n", i, x)
}
}
func while() {
for {
fmt.Printf("this is while")
}
}
func formap() {
map1 := make(map[string]string)
map1["A"] = "AAAA"
map1["B"] = "BBBB"
map1["C"] = "CCCC"
for k, v := range map1 {
fmt.Println("key:", k, "value:", v)
}
}
func forarray() {
array := [...]int64{1, 2, 3, 4}
for k, v := range array {
fmt.Println("key:", k, "value:", v)
}
}
func forslice() {
array := [...]int64{1, 2, 3, 4}
slice := array[:3:3]
for k, v := range slice {
fmt.Println("key:", k, "value:", v)
}
}
func array2() {
s := [...][2]string{{"a", "b"}, {"c", "d"}}
for _, v := range s {
for _, t := range v {
fmt.Println(t)
}
}
}
func main() {
array2()
forslice()
forarray()
formap()
while()
ranges()
xiao()
forcs(2)
fmt.Println(readFile("1.txt"))
fmt.Println(grade(100))
}
```