array
- package main
-
- import (
- "encoding/json"
- "fmt"
- )
-
- func test(data [2]string) {
- data[0] = "python"
- }
-
- func main() {
- var testArray = [2]string{
- "php",
- "java",
- }
- v, _ := json.Marshal(testArray)
- fmt.Println(string(v))
- test(testArray)
- v2, _ := json.Marshal(testArray)
- fmt.Println(string(v2))
- }
运行结果:
- ["php","java"]
- ["php","java"]
map
- package main
-
- import (
- "encoding/json"
- "fmt"
- )
-
- func test(data map[string]string) {
- data["1"] = "python"
- }
-
- func main() {
- var testMap = map[string]string{
- "1": "php",
- "2": "java",
- }
- v, _ := json.Marshal(testMap)
- fmt.Println(string(v))
- test(testMap)
- v2, _ := json.Marshal(testMap)
- fmt.Println(string(v2))
- }
运行结果:
- {"1":"php","2":"java"}
- {"1":"python","2":"java"}
slice
- package main
-
- import (
- "encoding/json"
- "fmt"
- )
-
- func test(data []string) {
- data[0] = "python"
- }
-
- func main() {
- var testSlice = []string{
- "php",
- "java",
- }
- v, _ := json.Marshal(testSlice)
- fmt.Println(string(v))
- test(testSlice)
- v2, _ := json.Marshal(testSlice)
- fmt.Println(string(v2))
- }
运行结果:
- ["php","java"]
- ["python","java"]
总结
- array 为值类型,这意味着当数组变量被赋值时,将会获得原数组的拷贝。新数组中元素的改变不会影响原数组中元素的值。
- slice、map 为引用类型,这意味着当元素被改变时,slice、map中元素的值会跟随改变。