03-Go語言語法基礎(二)

1. 條件查詢

1.1 if

  • if的條件裏不需要括號
  • if的條件裏可以賦值
  • if的提哦啊見裏賦值的變量作用域就在這個if語句裏
if contents, err := ioutil.ReadFile(filename); err != nil {
		fmt.Println(err)
	} else {
		fmt.Printf("%s\n", contents)
	}

1.2 switch

  • switch會自動break,除非使用fallthrough
  • switch後可以沒有表達式
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"
	}

2. 循環

2.1 for

  • for的條件裏不需要括號
  • for的條件裏可以省略初始條件,結束條件、遞增表達式
//省略初始條件,相當於while
for ; n > 0; n /= 2 {
	lsb := n % 2
	result = strconv.Itoa(lsb) + result
}

//省略初始條件與遞增條件,相當於while
for scanner.Scan() {
	fmt.Println(scanner.Text())
}

//無限循環
for {
	fmt.Println("abc")
}

3. 函數

  • 函數可以返回多個值
func div(a, b int) (int int) {
	return a / b, a % b
}
  • 函數返回多個值時可以起名字
  • 僅用於非常簡單的函數
  • 對調用者沒有區別
func div(a, b int) (q, r int) {
     q = a / b
     r = a % b
	return  
}
  • 函數作參數
func apply(op func(int, int) int, a, b int) int {
	p := reflect.ValueOf(op).Pointer()
	opName := runtime.FuncForPC(p).Name()
	fmt.Printf("Calling function %s with args "+
		"(%d, %d)\n", opName, a, b)

	return op(a, b)
}
  • 可變參數列表
func sum(numbers ...int) int {
	s := 0
	for i := range numbers {
		s += numbers[i]
	}
	return s
}

4. 指針

  • 指針不能運算
  • 值傳遞,引用傳遞?go語言只有值傳遞一種
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章