有意思的闭包行为

看一段代码先

package main

import (
    "strings"
    "fmt"
)

func shortenString(message string) func() string {
    return func() string {
        messageSlice := strings.Split(message, " ")
        wordLength := len(messageSlice)
        if wordLength < 1 {
            return "Nothing Left!"
        } else {
            messageSlice = messageSlice[:(wordLength - 1)]
            message = strings.Join(messageSlice, " ")
            return message
        }
    }
}

func main() {
    myString := shortenString("Welcome to concurrency in Go!...")
    fmt.Println(myString())
    fmt.Println(myString())
    fmt.Println(myString())
    fmt.Println(myString())
    fmt.Println(myString())
    fmt.Println(myString())
}

运行结果如下:
Welcome to concurrency in
Welcome to concurrency
Welcome to
Welcome

有没有发现,多次运行同一个闭包函数,其修改的上层函数传参值是同一个值

你可能感兴趣的:(有意思的闭包行为)