mirror of
https://github.com/adambard/learnxinyminutes-docs.git
synced 2024-12-23 17:41:41 +00:00
[go/en] Add value/reference semantics information for arr/slices.
This commit is contained in:
parent
e021d05c2f
commit
cd631729a8
@ -109,6 +109,11 @@ can include line breaks.` // Same string type.
|
||||
a5 := [...]int{3, 1, 5, 10, 100} // An array initialized with a fixed size of five
|
||||
// elements, with values 3, 1, 5, 10, and 100.
|
||||
|
||||
// Arrays have value semantics.
|
||||
a4_cpy := a4 // a4_cpy is a copy of a4, two separate instances.
|
||||
a4_cpy[0] = 25 // Only a4_cpy is changed, a4 stays the same.
|
||||
fmt.Println(a4_cpy[0] == a4[0]) // false
|
||||
|
||||
// Slices have dynamic size. Arrays and slices each have advantages
|
||||
// but use cases for slices are much more common.
|
||||
s3 := []int{4, 5, 9} // Compare to a5. No ellipsis here.
|
||||
@ -116,6 +121,11 @@ can include line breaks.` // Same string type.
|
||||
var d2 [][]float64 // Declaration only, nothing allocated here.
|
||||
bs := []byte("a slice") // Type conversion syntax.
|
||||
|
||||
// Slices (as well as maps and channels) have reference semantics.
|
||||
s3_cpy := s3 // Both variables point to the same instance.
|
||||
s3_cpy[0] = 0 // Which means both are updated.
|
||||
fmt.Println(s3_cpy[0] == s3[0]) // true
|
||||
|
||||
// Because they are dynamic, slices can be appended to on-demand.
|
||||
// To append elements to a slice, the built-in append() function is used.
|
||||
// First argument is a slice to which we are appending. Commonly,
|
||||
|
Loading…
Reference in New Issue
Block a user