func main() {
arr := [15]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}
for _, a := range arr {
_, s := fizzBuzz(a) // fizzBuzz有2個回傳值,可以用_ 不接回傳值
fmt.Printf("%v, %v\n", a, s)
}
}
func fizzBuzz(n int) (int, string) {
if n%3 == 0 && n%5 == 0 {
return n, "FizzBuzz"
}
if n%3 == 0 {
return n, "Fizz"
}
if n%5 == 0 {
return n, "Buzz"
}
return n, ""
}
func greeting() (name string, age int) { // 也可以宣告回傳值的變數名稱
name = "John"
ade = 12
return name, age // 常見寫法
return // naked return,不用再寫要回傳什麼
}
func main() {
nums(99, 100)
nums(1)
}
func nums (i ...int) { // 參數數量不固定的寫法,Go會把他轉成slice []int
fmt.Println(i)
}
func main() {
// anonymous function 匿名函式,func沒有名字,適合用在函式中,封裝小段的程式碼
sqr := func(num int) {
return num * num
}
fmt.Printf("result:" , sqr(3))
}
func main() {
name := "John"
age := 15
defer personAge(name, age)
age *= 2
personAge(name, age)
//output:
// John is 30 years old.
// John is 15 years old.
}
func personAge(name string, age int) {
fmt.Printf("%s is %d years old.", name, age)
}
https://www.tenlong.com.tw/products/9789863126706?list_name=c-go