函数的基本格式与使用

入参

  1. import (
  2. "fmt"
  3. )
  4. //带参数
  5. func hello(str string) {
  6. fmt.Println(str)
  7. }
  8. //不带参数
  9. func hello2() {
  10. fmt.Println("hello world2")
  11. }
  12. func main() {
  13. hello("hello world")
  14. hello2()
  15. }
  16. 输出结果:
  17. hello world
  18. hello world2

不定参数

//不定参数
func sum(args ...int)  {
    fmt.Println(args)
}

func main() {
    sum(1,2,3,4)
}

输出结果:
[1 2 3 4]

返回值

import (
    "fmt"
)

//不带返回值
func hello() {
    str := "hello world"
    fmt.Println(str)
}

//带返回值
func hello2() string {
    str := "hello world2"
    return str
}

func main() {
    str := hello()
    fmt.Println(str)
  hello2()
}

输出结果:
hello world
hello world2

匿名函数

package main

import (
    "fmt"
)

func main() {
    //写法1:带参数的匿名函数
    func(in_data string){
        var str string
        str = in_data
        fmt.Println(str)
    }("写法1:我是一个带参的匿名函数")

  //写法2:带参数的匿名函数
    f2:=func(in_data string){
        var str string
        str = in_data
        fmt.Println(str)
    }
    f2("写法2:我是一个带参的匿名函数")
}

输出结果:
写法1:我是一个带参的匿名函数
写法2:我是一个带参的匿名函数

递归

package main

import (
    "fmt"
)

//递归函数
func digui(num int) int {
    if num == 1{
        fmt.Println("我是递归函数")
        return num
    }
    return num+digui(num-1)
}

func main() {
    //递归
    num := digui(100)
    fmt.Println(num)
}

输出结果:
我是递归函数
5050

函数的作用域