实现说明
定长数组按值拷贝可以归结为函数 main、doubleArray。
这个文件只在 for i := range a 里循环。
使用要点
- 没有从任何仓库拉取东西;语言自带用到的全部 API。
- 直接运行文件,输出会带上标签,比如
original:、copied:、doubled:——输出的每一行都能指回产生它的那次调用。 - 执行文件,
main会按顺序走完doubleArray。
常见问题
运行「定长数组按值拷贝」会打印什么?
文件本身就是完整程序,直接运行——输出行带有 original:、copied:、doubled: 这类标签。
入口签名:func main()
核心语句
func doubleArray(a [3]int) [3]int {
for i := range a {
a[i] *= 2
}
return a
}
代码示例
package main
import "fmt"
func main() {
// Fixed-size arrays are value types: assignment and argument passing copy the whole array
var coords [3]int
coords[0], coords[1], coords[2] = 1, 2, 3
copied := coords
copied[0] = 99
fmt.Println("original:", coords)
fmt.Println("copied: ", copied)
// A function receives a copy too: changes inside do not affect the caller
doubled := doubleArray(coords)
fmt.Println("doubled: ", doubled)
fmt.Println("original:", coords)
// Slices reference the backing array: assignment shares data, one write is visible everywhere
view := coords[:]
view[0] = 7
fmt.Println("slice view:", view)
fmt.Println("original: ", coords)
// Length is part of the type: [3]int and [4]int cannot be assigned to each other
// var four [4]int = coords // compile error
fmt.Printf("types: %T vs %T\n", coords, view)
}
func doubleArray(a [3]int) [3]int {
for i := range a {
a[i] *= 2
}
return a
}