Composite data types for the Go language

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed. # The compound data type of the go language the composite data type of the #***go language is a combination of the underlying data types, consisting mainly of four * * arrays, slices (slice), map and struct * *. The size of the array and struct is fixed, the element type of the array is fixed, and the element type of the struct is not fixed. Map and slice are dynamic data structures that will grow dynamically based on demand. # #数组数组顾名思义就是同一类资源或者数据的集合. The following mainly describes the operation of the array: * * Initialization of the arrays **var arr [3]int//default initialization 0var Q [3]int = [3]int{1,2,3}q: = [...] Int{1,2,3}q: = [...] Int{90:-1}//key and value are assigned, the value of table 90 below is-1, the array length is access to the 91** array * * You can use an array subscript to access the elements in the array. As with the C language, array subscripts start at 0, and Len (array)-1 indicates the subscript of the last element. The following example iterates through an array of integers and prints the contents of the elements individually: Q: = [...] Int{1, 2, 3, 4}for I, Value: = Range Q {fmt. The Println (i, value)} array can be compared directly, when the elements in the array are the same, representing two arrays equal. ARR1: = [3]int{1, 2, 3}arr2: = [3]int{1, 2, 3}ARR3: = [3]int{1, 2, 4}fmt. Println (arr1 = = arr2, arr1 = = ARR3) The//true,false array can be passed as a function parameter, but since the array is actually copied as an argument, changing the value of the array inside the function does not affect the worth of the outer array. Func Arrisargs (arr [4]int) {arr[0] = 100}q: = [...] Int{1, 2, 3, 4}arrisargs (q) If you want to change: Func Arrisargs (arr *[4]int) {arr[0] = 100}q: = [...] Int{1, 2, 3, 4}arrisargs (&AMP;Q) but it's usually a slice to solve the problem, not an array. * * * slices and arrays are similar, except that their lengths are not fixed, that is, when defined []t does not need to specify a length. Arrays and slice are very closely related, and a slice can access some or all of the arrayData, and the bottom of the slice itself is a reference to an array. A slice consists of three parts: the pointer, the length, and the capacity. The built-in Len and CAP functions return the length and capacity of the slice, first of all, we'll look at how slice is created: create slice in two main ways: 1. Array-based creation. 2. Create directly 1. Base array creation: Arrvar: = [4]int{1, 2, 3,4}slicevar: = Arrvar[1:3] array Arrvar and slicevar the address is actually the same, that is, if you change the Slicevar inside the variable, Then the variables inside the Arrvar will change as well. 2. Direct creation can be created using the built-in make () function. In fact, an anonymous array is created, but we don't need to define it. Myslice1: = make ([]int,5)//Create an element number 5 Slice,cap is also 5myslice2: = make ([]int,5,10)//Create an element number 5 Slice,cap is 10myslice3: = [] int{1,2,3,4}//Create an element with a number of 4 slice,cap is 4var slice []int//Create an empty slice,cap and Len are 0 for why slice actually and the array is an address that, look at this picture below:! [] (Http://i.imgur.com/qpmWbdH.png) 3. The dynamic increment and decrement element said before, slice can be dynamically extended. However, slice dynamic expansion is a cost, that is, if the size of the premise, it is best to set the slice cap size, see a classic example: Func testappend () {var slice []intfor I: = 0; i <; i++ {s Lice = Append (slice, i) fmt. Printf ("%d cap =%d t%v\n", I, Cap (slice), slice)}}output:0 cap = 1 t[0]1 cap = 2 t[0 1]2 cap = 4 T[0 1 2]3 cap = 4 T[0 1 2 3]4 cap = 8 T[0 1 2 3 4]5 cap = 8 T[0 1 2 3 4 5]6 cap = 8 T[0 1 2 3 4 5 6]7 cap = 8 T[0 1 2 3 4 5 6 7]8 cap = t[0 1 2 3 4 5 6 7 8]9 CAP = t[0 1 2 3 4 5 6 7 8 9] As you can see, the cap is doubled when the capacity of slice equals Len. The underlying principle of append is that when the slice is full, re-establish a piece of memory and then copy the original data to the new memory. Therefore, the expansion of the capacity is the existence of memory creation and replication. This process will affect the speed of the system. Append can also be stitched together by two slice, but in a different format: oldslice: = []int{1, 2, 3, 4, 5}oldslice2: = []int{6, 7, 8, 9, 10}oldslice = Append (Oldslice, oldSlice2 ...)//must add three ... Two slice can also copy the contents directly, copy function: Slice1: = []int{1, 2, 3, 4, 5}slice2: = []int{5, 4, 3}copy (Slice2, Slice1)//Only the first 3 elements of Slice1 are copied to Slice2 copy (Slice1, SLICE2)// Only the 3 elements of the Slice2 are copied to the first 3 positions of Slice1 4. Use as a formal parameter to figure out slice we need to look at slice as a function parameter, take a look at a few examples: Func testslice (Myslice []int) { For I: = 0; I < 8; i++ {myslice = append (Myslice, i)}}eg1:myslice1: = Make ([]int, 8, 8) Testslice (myslice1[:0]) fmt. PRINTLN (Myslice1)//What is the result? Eg2:myslice1: = Make ([]int, 8, 8) Testslice (Myslice1) fmt. PRINTLN (Myslice1)//What is the result? The result of EG1 is [0 1 2 3 4 5 6 7],EG2 The result is [0 0 0 0 0 0 0 0]. To analyze the difference between the two instances, if it's not the same as what you think, then it proves that your understanding of slice is problematic (I've also struggled with it for a long time O (╯-╰) o) First analyze the first use case Testslice (myslice1[:0]), This means that a new slice is passed as a parameter to the function, and the new slice points to the address of the No. 0 element of the Myslice1, when you canTo test myslice1[:0] This thing's cap and Len, the values are 8 and 0 respectively, and then you append in the function is actually the new slice operation, but because the parameters of the outside function slice and Myslice1 is the same address, So the value outside is changed. To analyze the second instance, the second instance directly passes Myslice1 to the function, which is actually a copy of a slice, in the function append when your len is greater than the cap is worth it, this time the return is a new address. So the variables outside are not going to change. All is the default value 0 So what do we want to do to change the slice outside? The answer is the pointer, * * A pointer to what you want to change in the go language * *. Func TestSLice3 (Myslice *[]int) {for i: = 0; i < 8; i++ {*myslice = append (*myslice, i)}}myslice1: = Make ([]int, 0, 8) T EstSLice3 (&myslice1) for slice application basic can come here to end, you can test the use of slice more. * * In the Go language, all function parameters are value copy passed in, function parameters will no longer be the original variables when the function call ******# #map在C ++/java, map is generally encapsulated in the library, but in the go language map can be used directly. As a data structure for Key-value, map is a reference to a hash table. 1. DECLARE var myMap map[string] Personinfomymap is the declared variable name, Sting is the type of the corresponding key, and Peesoninfo is the type of value. 2. Create a map using the go language built-in make () to create. MyMap = Make (map[string] Personinfo) Create a fixed capacity Mapmymap = Make (map[string] personinfo,100) to create the initialization MAPmymap1: = map[string] int{"Hello": 1, "World": 2}3. Element deletion for the deletion of a map element, you can use the built-in delete function delete (MyMap, "123") if the key you passed in does not exist, then the call will not produce any errors. But if Mymap is nil then it will throw an exception. 4. The search for elements is traditionally done in map: 1. Declare a variable to be empty 2. Place the MapThe obtained value is saved to the variable 3. Determine if it is empty. However, this approach is too complex, can be implemented in the following way: Value,ok: = mymap["1234"]if ok{//representative found the//code processing Module}***# #结构体结构体是一种聚合的数据类型, is composed of 0 or more arbitrary types of values aggregated into the entity. Therefore, a struct cannot contain data of the struct type, but it can contain pointers to that struct type. 1. Definition of struct: type MyStruct struct{name string age intmale String}var Mystruct1 = mystruct{"Wenxuwan", and "man"}var mystruct2 = Mystruct{name: "Mashijie", Age:12, Male: "Man"}** struct literals do not have a short representation of the syntax **2 for anonymous members. Operation of struct type mystruct struct {name stringage in Tmale String}var mystest mystruct//define Structmystest.name = "Wenxuwan"//through. Operation Assignment Mystest.age = 28mystest.male = "Man" var my Structpoint *mystruct = &mystest//manipulate the structure body by pointer memberpoint: = &mystest.age//You can take a value on the member variable inside and then manipulate it with the pointer *memberpoint = FMT. Println (Mystructpoint.name, Mystructpoint.age, Mystructpoint.male) 3. Structure embedding and anonymous functions first we need to see why the struct needs to be nested, see the following example type Bird struct {method stringspecies Stringmale String}type Tiger struct {method stringspecies stringmale Stringyanchi int//tooth exclusive Fake The two structure above contains three identical variables, and of course there are different, and if we add other animals, we need to write a lot of repetitive code, which is time consuming and laborious. So we can write this way: type Animal struct {methodStringspecies Stringmale string}type Bird struct {animal animalfly bool}type Tiger struct {animal Animalyanchi int}var TIG ERs Tigertigers.animal.male = "Gong" tigers.animal.species = "Maoke" Tigers.animal.method = "Run" This is not the same as when we first started learning object-oriented inheritance. Back to the problem, the structure type became clearer after the change, but it also made it tedious to access each member. The **go language has a feature that lets us declare only one member's data type and not the name of the member, which is called an anonymous member. The data type of an anonymous member must be a named type or a pointer to a named type **type Bird struct {animalfly bool}type Tiger struct {Animalyanchi Int}var Tigers Tigertigers.male = "Nan" Tigers.method = "Pao" If your tiger also has a variable inside the animal, then this changes the tiger variable instead of the animal. 238 reads  ∙  1 likes  
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.