From cd631729a89faaf1cd77d7659e86c00be18e0309 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Petr=20Hou=C5=A1ka?= Date: Sat, 8 Feb 2020 23:11:33 +0100 Subject: [go/en] Add value/reference semantics information for arr/slices. --- go.html.markdown | 10 ++++++++++ 1 file changed, 10 insertions(+) (limited to 'go.html.markdown') diff --git a/go.html.markdown b/go.html.markdown index 49f1ade4..0c9082c6 100644 --- a/go.html.markdown +++ b/go.html.markdown @@ -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, -- cgit v1.2.3