01_无参无返的函数
func main() {
test() //直接写函数名调用;
}
func test() {
a := 10
fmt.Println("a=", a)
}
02_有参无返的函数
func main() {
test(10)
test01(12, "shalom")//调用时输入参数值;
}
func test(a int) {
fmt.Println("a=", a)
}
func test01(a int, b string) {
fmt.Printf("%d,%s", a, b)
}
03_不定参数类型
func main() {
test(1, 2, 3, 4, 5)
}
func test(a ...int) { //可输入多个int类型的参数,该参数一定要放在所有参数的最后;
fmt.Println("len(a)=", len(a))
for i := 0; i < len(a); i++ {
fmt.Printf("a(%d)=%d\n", i, a[i])
}
for i := range a { //效果和上面的for循环一样;
fmt.Printf("a(%d)=%d\n", i, a[i])
}
}
04_不定参数的传递
func main() {
test(1, 2, 3, 4, 5)
}
func test(args ...int) {
test01(args...)
test02(args[2:]...) //只传递args[2]右边的,包括args[2];
test03(args[:2]...) //只传递args[2]左边的,不包括args[2];
}
func test01(temp ...int) {
for i := range temp {
fmt.Printf("temp[%d]=%d\n", i, temp[i])
}
}
func test02(temp ...int) {
for data := range temp {
fmt.Println("data=", data)
}
}
func test03(temp ...int) {
for i := range temp {
fmt.Printf("temp[%d]=%d\n", i, temp[i])
}
}
05_一个返回值函数
func main() {
a := test()
fmt.Println(a)
b := test01()
fmt.Println("b=", b)
}
func test() int {
return 666
}
func test01() (v int) {
v = 123
return v
}
06_多个返回值
func main() {
a, b, c := test01()
fmt.Printf("%d,%d,%d\n", a, b, c)
d, e, f := test02()
fmt.Printf("%d,%d,%d\n", d, e, f)
}
func test01() (int, int, int) {
return 1, 2, 3
}
func test02() (a, b, c int) {
a = 4
b = 5
c = 6
return
}
07_有参有返函数
func main() {
max, min := MaxMin(12, 13)
fmt.Printf("max=%d,min=%d", max, min)
}
func MaxMin(a int, b int) (max, min int) {
if a > b {
max = a
min = b
} else {
max = b
min = a
}
return
}
08_函数递归调用
func main() {
test(5)
fmt.Println("shalom")
}
func test(a int) {
if a == 0 {
fmt.Println("a=", a)
return
}
test(a - 1) //自己调用自己;
fmt.Println("a=", a)
}
09_用递归实现数字累加
func main() {
var sum int
sum = test01(0)
fmt.Println("sum=", sum)
}
func test01(a int) int {
if a == 100 {
return 100
}
return a + test01(a+1)
}