1. 下面代碼輸出什麼?
func calc(index string, a, b int) int {
ret := a + b
fmt.Println(index, a, b, ret)
return ret
}func main() {
a := 1
b := 2
defer calc("1", a, calc("10", a, b))
a = 0
defer calc("2", a, calc("20", a, b))
b = 1
}
考點:defer執行順序
解答:
這道題類似第1題 需要注意到defer執行順序和值傳遞 index:1肯定是最後執行的,但是index:1的第三個參數是一個函數,所以最先被調用calc("10",1,2)==>10,1,2,3 執行index:2時,與之前一樣,需要先調用calc("20",0,2)==>20,0,2,2 執行到b=1時候開始調用,index:2==>calc("2",0,2)==>2,0,2,2 最後執行index:1==>calc("1",1,3)==>1,1,3,4
10 1 2 3
20 0 2 2
2 0 2 2
1 1 3 4
2. 請寫出以下輸入內容
func main() {
s := make([]int, 5)
s = append(s, 1, 2, 3)
fmt.Println(s)
}
考點:make默認值和append
解答:
make初始化是由默認值的哦,此處默認值爲0
[0 0 0 0 0 1 2 3]
大家試試改爲:
s := make([]int, 0)
s = append(s, 1, 2, 3)
fmt.Println(s)//[1 2 3]
@轉載,https://my.oschina.net/qiangmzsx/blog/1478739?p=1