16. Mutables(可变项)

Python没有指针的概念。去吧。但是,使用Go,您可以将数组或映射发送到函数中,对其进行修改而不会返回,并且会被更改。

16.1. Python

def upone(mutable, index):
    mutable[index] = mutable[index].upper()


list = ['a', 'b', 'c']
upone(list, 1)
print list  # ['a', 'B', 'c']

dict = {'a': 'anders', 'b': 'bengt'}
upone(dict, 'b')
print dict  # {'a': 'anders', 'b': 'BENGT'}

16.2. Go

package main

import (
    "fmt"
    "strings"
)

func upone_list(thing []string, index int) {
    thing[index] = strings.ToUpper(thing[index])
}

func upone_map(thing map[string]string, index string) {
    thing[index] = strings.ToUpper(thing[index])
}

func main() {
    // mutable
    list := []string{"a", "b", "c"}
    upone_list(list, 1)
    fmt.Println(list) // [a B c]

    // mutable
    dict := map[string]string{
        "a": "anders",
        "b": "bengt",
    }
    upone_map(dict, "b")
    fmt.Println(dict) // map[a:anders b:BENGT]
}