Go language 4-arrays, slices, and maps

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

1. Arrays
Array length definition cannot be modified, the number of array elements is obtained through the built-in function Len ()

1)类型
    //长度为32的byte数组,每个元素为一个字节    [32]byte    //长度为2*N的复杂类型数组    [2structint32}    //长度100的指针数组    [100]*float64    //二维数组,等同于[2]([3]int)    [2][3]int    //三维数组    [2][2][2]float64
2)定义
    //Defines an array of length 5, which is initialized by default with 0 values of type int (0)Arr: =[5]int{}//As in the above sentence    varArr[5]int=[5]int{}//define an array of length 5, where arr[0] will be initialized to 1 and the rest is still 0Arr: =[5]int{1}//define an array of length 5, where arr[0], arr[4] will be initialized to 1, and the rest is still 0Arr: =[5]int{0: 1, 4: 1}//Defines an array of length 5, which is initialized by default with 0 values of type int (0)Arr: =New([5]int)//define and initialize an array, which automatically infers the length of the array ([...] ), this needs to be different from the definition of the following slices (no ...)Arr: = [...]int{1,2,3,4,5}//define and initialize an array, and will automatically infer that the length is 5,arr[4] will be initialized to 1, the rest is still 0Arr: = [...]int{4: 5}
3)遍历
 //and other programming language types traverse the way . Span class= "Hljs-comment" >//gets the length of the array arr  lenth: = len  (arr) 
   
    for  I: =
     0 ; i < lenth; i++ {
    //uses array indexing to traverse the array  fmt. Print (Arr[i], 
    )} //use range to iterate through the array, range has two return values, 1 is index, 2 is the value  for  i, V: = range  arr {fmt. Print ( "[" , I, "]=" , V, )} 
    
4)比较操作在两个数据是同一类型(长度及元素类型)时,可以使用==与!=对两个数组进行比较,但不能使用<或>。注:Go语言中数组是一个值类型,所有值类型变量在赋值和作为参数传递时都将产生一次复制动作,    传入函数中的数组仅是该数组的一个副本,因此就无法对其进行修改,如果此时的数组较大时,    将会降低程序的效率,关于这种场景的解决,下面的切片会进行讲解。

2. Slicing

在上面我们提到数组两个特点:1、数据长度在定义后无法再次进行修改;2、数据是值类型,每次传递都将产生一个副本;而Slice(切片)正是为解决以上两个问题而存在。从表象看,切片是一个指向原始数组的指针,但实际上,切片拥有自己的数据结构1、一个指向原生数组的指针2、数组切片中的元素个数3、数组切片已分配的存储空间这里需要区分两个概念,长度:切片已使用的大小,从切片头开始算起,使用内置函数len()获取容量:切片允许使用的大小,从切片头开始算起,至底层数组末尾,使用内置函数cap()获取,      当切片长度超过容量时,会重新分配一个原容量两倍的容间,并将值复制过去,与Java      中的ArrayList有点类似,要注意扩容后的内存地址与原内存地址不一样。1)定义
    //define an array here firstArr: =[5]int{}//Based on the data defined above, define a slice that points to the ARR index value in the [0,5] range (left open right)    //[M,n] here can also be written in several ways, such as [: 5] means [0,5], [1:] means [1,len (arr)], [:] means [0,len (arr) ]Arrslice: = arr[0: 5]//define a slice with a length of 5 and a capacity of 5, note that the difference between the definition of the above array and the definition of the array is in parentheses ...Arrslice: = []int{1, 2, 3, 4, 5}//define a slice with a length of 5 and a capacity of 5Myslice: = Make([]int, 5)//define a slice with a length of 5 and a capacity of 10Myslice: = Make([]int, 5, ten)//Slicing on slices, this is called Reslice, where [m:n] must meet 0<=m<n<=cap (Myslice)-MMySlice2: = myslice[:]
在reslice的情况下,有很多地方需要注意,因为原slice与reslice实际底层使用的是同一块内存空间,当两个的长度都在底层数组的长度内时,两者共享的都是同一块容间,当有一个超过之后,这种情况将会被打破。如下面的代码所示:
Myslice: = Make([]int, 5, 6)//i.e. myslice[1] corresponds to myslice2[1], etc.MySlice2: = Myslice[1:]//This is equivalent to also the value of myslice2[0] has been modifiedMyslice[1]  =Ten    //append is a built-in function that represents the append value to the slice, the myslice length is increased, but the mySlice2 length remains the same.Myslice =Append(Myslice, 1)//The value of myslice[5] will be overwritten with 2, that is, the value of the previous line of code is overwrittenMySlice2 =Append(MySlice2, 2)The space allocation will occur when you have exhausted all the space and added the value through the code aboveMySlice2 =Append(MySlice2,7)//This changes only myslice2[0], while myslice[1] does not changeMySlice2[0] =-1
2)遍历与数组遍历一样,这里就不复述了3)切片的增减
    //Add a value of 1 at the end of the slice and, if it exceeds the capacity, will result in a redistribution of the capacitance, which will be twice times the original capacityMyslice =Append(Myslice, 1)//Add multiple values at the end of the sliceMyslice =Append(Myslice, 1, 2, 3)//Append an array at the end of the slice, where the "..." is required, otherwise it compiles an error, which means that the array is broken and passed inMyslice =Append(Myslice,arr ...)//Add another slice at the end of the slice, where the MySlice2 [:] is omitted.Myslice =Append(Myslice,myslice2 ...)//Slice minus, this means delete myslice[1], the length of the slice decreases, but the capacity does not changeMyslice =Append(myslice[: 1],myslice[2:]...)//Slice minus, if you want to delete the end of the slice, you can use the Reslice method to implement theMyslice = Myslice[0:Len(Myslice)-1]
4)内容复制用于将内容从一个数组切片复制到另一个数组切片。如果两个切片不一样大,将以较小切片的元素个数进行复制
    //这里要注意顺序,与Java的那种前者from后者to相反    copy(targetSlice,sourceSlice)

3. Map
Unordered set of key-value pairs, built directly into the system without the need to introduce additional packages

1)声明var 变量名 map[键类型]值类型
    varmap[int]string
2)创建
    //Create a key of int, a value of string map,mymap need to be declared firstMyMap = Make(Map[int]string)//declaration + CreateMyMap: = Make(Map[int]string)//Create a map with a capacity of 100MyMap = Make(Map[int]string, the)//declaration + CreateMyMap =Map[int]string{}//declaration + Create + initializeMyMap =Map[int]string{1:"1"}
3)元素赋值、删除、查找
    //增加或修改key=123对应的元素值为字符型"123"    myMap[123"123"    //删除key=123对应的元素    delete(myMap,123)    //查找key=123对应的元素,该操作有两个返回值,多返回值知识点将在函数相关内容说到,    //返回值1为对应的值,返回值2为是否包含该key    v, ok := myMap[123]

This article introduces the two most commonly used data structures in programming, arrays and maps, and introduces a scalable "array" and can be seen as an array of pointers-slices, arrays and slices have too many similarities, but at the same time there are differences, so as a novice to pay special attention.

No smell (Unknow) "Go Programming Basics"
Xu Xiwei's "Go Language Programming"

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.