var arr = [1, 2, 3];
var arr1 = [...arr, 4, 5, 6];
1 package main
2
3 import "fmt"
4
5 func main() {
6 a := make([]int, 3)
7 fmt.Println(a)
8
9 }
package main
import "fmt"
func main() {
a := []string{"a", "b", "c", "d", "e"}
fmt.Println("before call function:", a)
changeZeroElementA(a)
fmt.Println("after call function:", a)
b := [5]string{"a", "b", "c", "d", "e"}
fmt.Println("before call function:", b)
changeZeroElementB(b)
fmt.Println("after call function:", b)
}
func changeZeroElementA(arr []string) {
//arr = []string{"X", "Y"}
arr[0] = "changed"
}
func changeZeroElementB(arr [5]string) {
arr[0] = "changed"
}
before call function: [a b c d e]
after call function: [changed b c d e]
before call function: [a b c d e]
after call function: [a b c d e]
package main
import "fmt"
func main() {
a := []string{"a", "b", "c", "d", "e"}
fmt.Println("before call function:", a)
changeZeroElementA(a)
fmt.Println("after call function:", a)
b := [5]string{"a", "b", "c", "d", "e"}
fmt.Println("before call function:", b)
changeZeroElementB(b)
fmt.Println("after call function:", b)
}
func changeZeroElementA(arr []string) {
arr = []string{"X", "Y"}
arr[0] = "changed"
}
func changeZeroElementB(arr [5]string) {
arr[0] = "changed"
}
1 before call function: [a b c d e]
2 after call function: [a b c d e]
3 before call function: [a b c d e]
4 after call function: [a b c d e]
看到这里是不是有些奇怪,其实go里面一切都是值传递。这里有全方面的解释:https://stackoverflow.com/questions/39993688/are-golang-slices-pass-by-value