練習Go變參時遇到一個報錯:used as value 代碼如下:
// 錯誤代碼
func myfunc(arg ...int) {
for _, n := range arg {
fmt.Printf("And the number is: %d\n", n)
}
}
func main() {
fmt.Printf(myfunc(1, 2, 3, 4, 5))
}
// 報錯 myfunc(1, 2, 3, 4, 5) used as value
// 正確代碼
func myfunc(arg ...int) {
for _, n := range arg {
fmt.Printf("And the number is: %d\n", n)
}
}
func main() {
myfunc(1, 2, 3, 4, 5)
}
// 結果:
//And the number is: 1
//And the number is: 2
//And the number is: 3
//And the number is: 4
//And the number is: 5
// 或者 正確代碼
func myfunc(arg ...int) int {
m := 0
for _, n := range arg {
m += n
}
return m
}
func main() {
fmt.Printf("m = %d", myfunc(1, 2, 3, 4, 5))
}
// 結果:m = 15
從上面代碼可以看出myfunc()函數是沒有返回值的,直接調用就可以,不需要使用fmt包或者給返回值進行輸出。
