Difference golang slices and arrays

Long time did not write the blog, this time to study the case go all right this language.

We first describes the differences and usage go down in the arrays and slices

Having said that let's look at the code segment bar

var arr1 [3] you 
var arr2 [3] you = [3] you {1, 2, 3} 
fmt.Println (arr1) 
fmt.Println (arr2)

 I declare two arrays, initialization, and not initialized

 And then run the code output [000] [123] have found no other language is not the same place, attentive friend should have discovered the default value of 0 in the go language

D: / Program / golang / Hello golang / the src / B / b.exe [D: / Program / golang / Hello golang / the src / B] 
[0 0 0] 
[2. 3. 1] 
Success: Process exit code of 0.

  

Then we look at the cut, sliced ​​and arrays like. It can be said is a special array

var slice []int = []int{3, 6}
fmt.Println(slice)
slice = append(slice, 1, 2, 3, 5, 8)
fmt.Println(slice)

Declares a slice int type array slice slice length is variable, we can add value to the inside of the same type by the append method

Console and run the code printed exactly as we expected

D: / Program / golang / Hello golang / the src / B / b.exe [D: / Program / golang / Hello golang / the src / B] 
[. 3. 6] 
[2. 3. 1. 6. 8. 3. 5] 
Success: Process Exit Code 0.

 Above us about the use of sections and arrays, and now look at the difference between them

fmt.Println("数组***********************************")
var arr1 [3]int = [3]int{1, 2, 3}
var arr2 [3]int = arr1
fmt.Println(arr1, arr2)
arr2[0] = 10002
fmt.Println(arr1, arr2)

fmt.Println("切片***********************************")
var slice1 []int = []int{1, 2, 3}
var slice2 []int = slice1
fmt.Println(slice1, slice2)
slice2[0] = 10002
fmt.Println(slice1, slice2)

The output can be seen as a value array slice is a copy of the reference

D: / program / GoLang / hello golang / src / b / b.exe [D: / program / GoLang / hello golang / src / b] 
array ***************** ****************** 
[123] [123] 
[123] [1,000,223] 
chips *********** ************************ 
[123] [123] 
[1,000,223] [1,000,223] 
success: process exit Code 0 .

  Well, how to write more than today, like the point of a friend to help Zambia

Guess you like

Origin www.cnblogs.com/blog-196/p/11141356.html