【GoLang】golang中可以直接返回slice吗?YES
结论:
可以,slice本质是结构体,返回slice时返回的是结构体的值,结构体的指针、len、cap等信息也全部返回了。 如下: type slice struct { start *uintptr length int64 capacity int64 } example := make([]byte, 0, 10) // slice{start:calloc(10), length:0, capacity:10} return example // return the VALUE slice{start:calloc(10), length:0, capacity:10} example2 := make([]byte, len(example), cap(example)) copy(example2, example) return example2 // return the VALUE slice{start:calloc(10), length:0, capacity:10} but its a new COPY
package main /* How to return by value */ import "fmt" func getArr() ([]int,[]int) {a:=[]int{1,2}; return a,a} func main() { arr1,arr2 := getArr() arr1[1] = 3 fmt.Println(arr1,arr2) }
参考资料:
https://groups.google.com/forum/#!topic/golang-nuts/LA-cTnKY3cw
https://play.golang.org/p/bVP5wPCcQ2