06_多个返回值.go
package main //必须
import "fmt"
//多个返回值
func myfunc01() (int, int, int) {
return 1, 2, 3
}
//go官方推荐写法
func myfunc02() (a int, b int, c int) {
a, b, c = 111, 222, 333
return
}
func myfunc03() (a, b, c int) {
a, b, c = 111, 222, 333
return
}
func main() {
//函数调用
a, b, c := myfunc02()
fmt.Printf("a = %d, b = %d, c = %d\n", a, b, c)
}
07_有参有返回值.go
package main //必须
import "fmt"
//函数定义
func MaxAndMin(a, b int) (max, min int) {
if a > b {
max = a
min = b
} else {
max = b
min = a
}
return //有返回值的函数,必须通过return返回
}
func main() {
max, min := MaxAndMin(10, 20)
fmt.Printf("max = %d, min = %d\n", max, min)
//通过匿名变量丢弃某个返回值
a, _ := MaxAndMin(10, 20)
fmt.Printf("a = %d\n", a)
}
08_普通函数的调用流程.go
package main //必须
import "fmt"
func funcc(c int) {
fmt.Println("c = ", c)
}
func funcb(b int) {
funcc(b - 1)
fmt.Println("b = ", b)
}
func funca(a int) {
funcb(a - 1)
fmt.Println("a = ", a)
}
func main() {
funca(3) //函数调用
fmt.Println("main")
}
09_函数递归调用的流程.go
package main //必须
import "fmt"
func test(a int) {
if a == 1 { //函数终止调用的条件,非常重要
fmt.Println("a = ", a)
return //终止函数调用
}
//函数调用自身
test(a - 1)
fmt.Println("a = ", a)
}
func main() {
test(3)
fmt.Println("main")
}
10_数字累加.go
package main //必须
import "fmt"
//实现1+2+3+……100
func test01() (sum int) {
for i := 1; i <= 100; i++ {
sum += i
}
return
}
func test02(i int) int {
if i == 1 {
return 1
}
return i + test02(i-1)
}
func test03(i int) int {
if i == 100 {
return 100
}
return i + test03(i+1)
}
func main() {
var sum int
//sum = test01()
//sum = test02(100)
sum = test03(1)
fmt.Println("sum = ", sum)
}
网友评论