Go语言学习之函数(The way to go)

生命不止,继续Go go go.

变量介绍完了,流程控制介绍完了,也该轮到函数了。
go中,使用关键字func进行函数声明:

func function_name( [parameter list] ) [return_types]{
   body of the function
}

比如,声明一个函数,交换两个字符串:

func swap(x, y string) (string, string) {
    return y, x
}

函数的左花括号也不能另起一行

package main

import ( "fmt" "math/rand" ) func main() { fmt.Println("My favorite number is", rand.Intn(10)) }

错误:unexpected semicolon or newline before {

不允许函数内嵌定义

package main

import "fmt"

func main() {
    func swap(x, y string) (string, string) {
    return y, x
    }
    a, b := swap("hello", "world")
    fmt.Println(a, b)
}

错误:syntax error: unexpected swap, expecting (

支持多返回值、支持命名返回值

package main

import "fmt"

func split(sum int) (x, y int) {
    x = sum * 4 / 9
    y = sum - x
    return
}

func main() {
    fmt.Println(split(17))
}

函数只能判断是否为nil
什么是nil?
In Go, nil is the zero value for pointers, interfaces, maps, slices, channels and function types, representing an uninitialized value.

package main

import "fmt"

func add(a, b int) int {
    return a + b
}

func main() {
    fmt.Println(add == nil)
    //fmt.Println(add == 1)  //错误 mismatched types func(int, int) int and int)
}

参数视为局部变量,因此不能声明同名变量

package main

import "fmt"

func add(a, b int) int {
    a := 2
    var b int
    return a + b
}

func main() {
    fmt.Println(add(1,2))
}

错误:
no new variables on left side of :=
b redeclared in this block

不支持默认参数、已”_”命名的参赛也不能忽略

package main

import "fmt"

func add(a, b int, _ bool) int {
    return a + b
}

func main() {
    fmt.Println(add(1,2, true))
    //fmt.Println(add(1,2) // 错误:not enough arguments in call to add
}

支持可变参数

package main

import "fmt"

func test(str string, a ...int) {
    fmt.Println("%T, %v\n", str, a)
}

func main() {
    test("a", 1, 2, 3)
}

输出:a [1 2 3]

可以在函数内定义匿名函数

package main

import "fmt"


func main() {
    func (s string) {
        fmt.Println(s)
    } ("hello, go!")
}

输出:hello, go!

闭包
这里就简答介绍一下闭包的语法:

package main

import "fmt"

// This function `intSeq` returns another function, which
// we define anonymously in the body of `intSeq`. The
// returned function _closes over_ the variable `i` to
// form a closure.
func intSeq() func() int {
    i := 0
    return func() int {
        i += 1
        return i
    }
}

func main() {

    // We call `intSeq`, assigning the result (a function)
    // to `nextInt`. This function value captures its
    // own `i` value, which will be updated each time
    // we call `nextInt`.
    nextInt := intSeq()

    // See the effect of the closure by calling `nextInt`
    // a few times.
    fmt.Println(nextInt())
    fmt.Println(nextInt())
    fmt.Println(nextInt())

    // To confirm that the state is unique to that
    // particular function, create and test a new one.
    newInts := intSeq()
    fmt.Println(newInts())
}

你可能感兴趣的:(函数,go语言)