Fixed Arrays Copy By Value
Assign or pass [N]T arrays and each call copies the whole value, while a slice view of the same array keeps sharing the underlying storage.
Code
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
}How it works
Fixed Arrays Copy By Value keeps everything in the functions main and doubleArray.
The cycling part of this snippet is for i := range a.
Watch out for
- No external surface at all — the standard library supplies all behavior.
Putting it to use
Entry signature: func main()
Look for the original:, copied:, doubled: prefixes when the file runs; they tie each line to its step.
Launch the file; main takes over and steps through doubleArray.
The core lines of the flow
func doubleArray(a [3]int) [3]int {
for i := range a {
a[i] *= 2
}
return a
}
Interactive Tools for This Topic
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- What does Fixed Arrays Copy By Value print when run?
- Run it as a complete program — the output lines carry labels such as `original:`, `copied:`, `doubled:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.