Go language Development (iii), go language built-in container

Source: Internet
Author: User
Tags array length

Go language Development (iii), go language built-in container one, go language array 1, go language array introduction

The go language provides the data structure of the array type.
An array is a series of numbered and fixed-length data items with the same unique type, which can be any primitive type such as XXX, a string, or a custom type.
Relative to the declaration NUMBER0, Number1, ..., and number99 variables, using array form numbers[0], numbers[1] ..., numbers[99] more convenient and easy to expand.
Array elements can be read (or modified) by index (position), index starting at 0, index of first element is 0, second index is 1, and so on.

2. Go Language Array declaration

The Go language Array declaration needs to specify the element type and the number of elements, with the syntax in the following format:
var variable_name [SIZE] variable_type
The above is how one-dimensional arrays are defined. The array length must be an integer and greater than 0. For example, the following defines an array balance length of 10 for type float32:
var balance [10] float32

3. Go Language Array initialization

var balance = [5]float32{1000.0, 2.0, 3.4, 7.0, 50.0}
The number of elements in the {} initialization array cannot be greater than the number in [].
If you ignore numbers in [] without setting the array size, the go language sets the size of the array based on the number of elements:
var balance = [...]float32{1000.0, 2.0, 3.4, 7.0, 50.0}
The instance is the same as the previous instance, although the size of the array is not set.
balance[4] = 50.0
The above instance reads a FIFTH element. Array elements can be read (or modified) by index (position), index starting at 0, index of first element is 0, second index is 1, and so on.

4, go array element access

Array elements can be read by index (position). The format is an array name followed by brackets, and the values in brackets are indexed. For example:
var salary float32 = balance[9]
The above instance reads the value of the 10th element of the array balance.
The following shows an example of an array full operation (declaration, assignment, access):

package mainimport "fmt"func main() {   var n [10]int /* n 是一个长度为 10 的数组 */   var i,j int   /* 为数组 n 初始化元素 */   for i = 0; i < 10; i++ {      n[i] = i + 100 /* 设置元素为 i + 100 */   }   /* 输出每个数组元素的值 */   for j = 0; j < 10; j++ {      fmt.Printf("Element[%d] = %d\n", j, n[j] )   }}
5, Go language Multidimensional array introduction

The Go language supports multidimensional arrays, and the following are common multidimensional array declarations:
var variable_name [SIZE1][SIZE2]...[SIZEN] variable_type
The following example declares a three-dimensional array of integers:
var threedim [5][10][4]int

6, go language two-dimensional array declaration

Two-dimensional arrays are the simplest multidimensional arrays, and two-dimensional arrays are essentially composed of one-dimensional arrays. The two-dimensional array is defined in the following way:
var arrayName [ x ][ y ] variable_type
Variable_type is the data type of the go language, Arrayname is an array name, two-dimensional arrays can be considered a table, X is a row, Y is a column, and a two-dimensional array A is shown as three rows and four columns:

Elements in a two-dimensional array can be accessed through a[I [j].
Initialize a two-dimensional array
Multidimensional arrays can be initialized with curly braces. The following instance is a two-dimensional array of 3 rows and 4 columns:

a = [3][4]int{{0, 1, 2, 3} ,   /*  第一行索引为 0 */{4, 5, 6, 7} ,   /*  第二行索引为 1 */{8, 9, 10, 11}   /*  第三行索引为 2 */}

Accessing two-dimensional arrays
A two-dimensional array is accessed by specifying coordinates. The row and column indexes in an array, for example:
int val = a[2][3]
Two-dimensional arrays can use loop nesting to output elements:

package mainimport "fmt"func main() {   /* 数组 - 5 行 2 列*/   var a = [5][2]int{ {0,0}, {1,2}, {2,4}, {3,6},{4,8}}   var i, j int   /* 输出数组元素 */   for  i = 0; i < 5; i++ {      for j = 0; j < 2; j++ {         fmt.Printf("a[%d][%d] = %d\n", i,j, a[i][j] )      }   }}
7. Array parameter passing

If you pass an array argument to a function, you need to declare the parameter to be an array when the function is defined. An array parameter is passed as a value pass, and if you want to modify the value of an array's elements inside a function, you need to pass an array pointer. In general, there are two ways to declare an array parameter of a function:
A, parameter specifies the size of the array

func sum(arr [5] int, size int) int{   var c int = 0   var i int   for i = 0; i < size;i++{      c += arr[i]   }   return c}

B, parameter does not specify array size

 func getAverage(arr []int,size int) float32 {   var i int   var avg float32   var sum int   for i = 0; i < size; i++{      sum += arr[i]   }   avg = float32(sum / size)   return avg;}

Array usage Examples:

package mainimport "fmt"func getAverage(arr []int,size int) float32 {   var i int   var avg float32   var sum int   for i = 0; i < size; i++{      sum += arr[i]   }   avg = float32(sum / size)   return avg;}func sum(arr [5] int, size int) int{   var c int = 0   var i int   for i = 0; i < size;i++{      c += arr[i]   }   return c}func main() {   var a [] int   a = []int{1,2,6,90}   var c float32   c = getAverage(a,4)   fmt.Println(c)   var b [5] int   b = [5]int{1,2,3,4,5}   var d int = sum(b,5)   fmt.Println(d)}
Second, go language slice 1, slice definition

The Go language slice is an abstraction of an array.
Since the length of the go array is immutable, go provides a flexible, powerful built-in type slice ("dynamic array"), the length of the slice is not fixed, you can append the element, which may increase the capacity of the slice when appended.
You can declare an array of unspecified size to define a slice:
var identifier []type
Use the Make () function to create a slice:
var slice1 []type = make([]type, len)
You can specify the capacity, where capacity is an optional parameter.
make([]T, length, capacity)
Len is the length of the array and is also the initial length of the slice.

2. Slicing initialization

s :=[] int {1,2,3 }
Direct initialization of the slice, [] means the slice type, and {1,2,3,cap=len=3} The initialization value is sequentially
s := arr[:]
Initializing slices using the array arr reference
s := arr[startIndex:endIndex]
Create an element in Arr from subscript startindex to endIndex-1 as a new slice
s := arr[startIndex:]
The default endindex will represent the last element to arr
s := arr[:endIndex]
The default startindex will represent the start of the first element in arr
s1 := s[startIndex:endIndex]
Initializing slices by slicing s S1
s :=make([]int,len,cap)
Initialize slice s,[]int with built-in function make () to identify slices whose element type is int

3. Slicing operation

Slices are indexable and can be obtained by the Len () method.
The slice provides a method for calculating the capacity of the CAP () to measure how long the slice can reach.

package mainimport "fmt"func printSlice(x []int){   fmt.Printf("len=%d cap=%d slice=%v\n",len(x),cap(x),x)}func main() {   var slice1 [] int   var slice2 [] int = make([]int, 6)   slice1 = []int{1,2,3,4}   slice2 = []int{1,2,3}   printSlice(slice1)   printSlice(slice2)   s :=[] int {1,2,3 }   fmt.Println(s)}
4. Nil Slice

The slice defaults to nil before being initialized, with a length of 0.

package mainimport "fmt"func printSlice(x []int){   fmt.Printf("len=%d cap=%d slice=%v\n",len(x),cap(x),x)}func main() {   var slice1 [] int   printSlice(slice1)   if slice1 == nil{      fmt.Println("slice1 is nil")   }  }
5. Slice interception

You can set the Intercept slice [lower-bound:upper-bound] by setting the lower and upper limits.

package mainimport "fmt"func printSlice(x []int){   fmt.Printf("len=%d cap=%d slice=%v\n",len(x),cap(x),x)}func main() {   //创建切片   numbers := []int{0,1,2,3,4,5,6,7,8}   printSlice(numbers)   //打印原始切片   fmt.Println("numbers ==", numbers)   //打印子切片从索引1(包含) 到索引4(不包含)   fmt.Println("numbers[1:4] ==", numbers[1:4])   //默认下限为0   fmt.Println("numbers[:3] ==", numbers[:3])   //默认上限为 len(s)   fmt.Println("numbers[4:] ==", numbers[4:])   numbers1 := make([]int,0,5)   printSlice(numbers1)   //打印子切片从索引0(包含)到索引2(不包含)   number2 := numbers[:2]   printSlice(number2)   //打印子切片从索引2(包含)到索引5(不包含)   number3 := numbers[2:5]   printSlice(number3)}
6, the nature of the slice

A slice is essentially a view of an array. A slice is a description of an array fragment that contains a pointer to an array, the length and capacity of the fragment (the maximum length of the fragment). The relationship between the slice and the underlying array is as follows:

The internal implementation of the slice is as follows:

The inside of the slice contains a pointer to a location in the underlying array, the slice length information, and the tile capacity information.
The slice can be scaled backwards and cannot be scaled forward.
S[i] Way to reference slice data can not go beyond Len (s), the backward extension can not go beyond the underlying array cap (s).

package mainimport "fmt"func sliceExtend(){   //定义数组   arr := [...]int{0,1,2,3,4,5,6,7}   s1 := arr[2:6]   s2 := s1[3:5]   s3 := arr[2:]   s4 := arr[:6]   s5 := arr[:]   printSlice(s1)//len=4 cap=8 slice=[2 3 4 5]   printSlice(s2)//len=2 cap=5 slice=[5 6]   printSlice(s3)//len=8 cap=8 slice=[2 3 4 5 6 7]   printSlice(s4)//len=6 cap=10 slice=[0 1 2 3 4 5]   printSlice(s5)//len=10 cap=10 slice=[0 1 2 3 4 5 6 7]   //对切片中数据进行修改,底层数组数据也被修改   s1[0] = 100   printSlice(s1)//len=4 cap=8 slice=[100 3 4 5]   printSlice(s5)//len=10 cap=10 slice=[0 1 100 3 4 5 6 7]   fmt.Println(arr)//[0 1 100 3 4 5 6 7]   s1 = s1[2:6]   printSlice(s1)//len=4 cap=6 slice=[4 5 6 7]   //切片不能引用底层数组范围外的数据   //printSlice(s1[2:9])//报错}func main() {   sliceExtend()}
7. Slice Append and copy

If you want to increase the capacity of a slice, you must create a new larger slice and copy the contents of the original Shard.
The append () function appends one or more elements to one slice.
The copy (DEST,SRC) function copies the dest slices to the src slice.
When an element is appended, if the slice goes beyond the cap, the system assigns a larger underlying array to the slice, and the capacity of the underlying array increases twice each time the underlying array needs to be reassigned.

Package Mainimport "FMT" func sliceoperate () {var numbers = [3]int{0,1}//array S1: = numbers[1:]//slice s1[0] = 101//Modified Slice The value of the element Printslice (S1)//len=2 cap=2 slice=[101 0] fmt. PRINTLN (Numbers)//[0 101 0]//Append an element to the slice S1 = append (S1, 2) printslice (S1)//len=3 cap=4 slice=[101 0 2]//Add an element to the slice , has exceeded the cap, the system allocates a larger underlying array for the slice S1 = append (S1, 3) printslice (S1)//len=4 cap=4 slice=[101 0 2 3] fmt.  PRINTLN (Numbers)//[0 101 0]//Add multiple elements simultaneously, the system assigns a new underlying array to the slice S1 = append (S1, 4,5,6) printslice (S1)//len=7 cap=8 slice=[101 0 2 3 4 5 6] FMT. PRINTLN (Numbers)//[0 101 0]//create slice Numbers1,len same as numbers slice, cap is twice times s2: = Make ([]int, Len (S1), (Cap (S1))//copy number s content to numbers1 copy (S2,S1) printslice (S2)//len=7 cap=16 slice=[101 0 2 3 4 5 6]//remove 0 from s2 s2 = append (S2[0:1], s2[2:    ]...) Printslice (S2)//len=6 cap=16 slice=[101 2 3 4 5 6]//Delete First element front: = s2[0] FMT.   PRINTLN (front)//101 s3: = s2[1:] Printslice (S3)//len=5 cap=15 slice=[2 3 4 5 6]//delete last element tail: = S2[len (s2)-1] S4 : = S2[:len (s2)-1] fmt. Println (tail)//6 Printslice (S4)//len=5 cap=16 slice=[101 2 3 4 5]}func main () {sliceoperate ()}
Introduction to go language Map1, go language map

A MA is a collection of unordered key-value pairs. The most important point of map is to quickly retrieve data by key.
A map is a collection that you can iterate over. Map is implemented using a hash table, the map is unordered, and the order of return cannot be determined.

2, Go language map definition

You can use the built-in function make, or you can use the Map keyword to define a map:

//声明变量,默认map是nilvar map_variable map[key_data_type]value_data_type//使用make函数map_variable := make(map[key_data_type]value_data_type)

If you do not initialize the map, a nil map is created. The nil map cannot be used to store key-value pairs.

//map集合创建var countryCapitalMap map[string]string//countryCapitalMap==nilcountryCapitalMap = make(map[string]string)//countryCapitalMap == empty map
3. Go Language Map operation

Get element: Map[key]
When key does not exist, the initial value of the value type is obtained.
Use Value,ok: = Map[key] To determine if there is a key.
Use range to traverse key, traverse Key,value pair, and traverse not guarantee order.
Use Len to get the number of elements in the map.
Map uses a hash table and must be able to compare equality.
The built-in types of slice, map, and function can be used as key. The struct type can be a key if it does not contain the slice, map, and Func fields.
The delete () function is used to delete the elements of the collection, with the parameter map and its corresponding key.

Package Mainimport "FMT" func Mapdemo () {//map collection create var countrycapitalmap map[string]string Countrycapitalmap = Make (M ap[string]string)//map insert Key-value to countrycapitalmap["France"] = "Paris" countrycapitalmap["Italy"] = "Rome" Countr ycapitalmap["Japan" = "Tokyo" countrycapitalmap["India"] = "New Delhi"//map Value modification countrycapitalmap["France"] = "PARIS"//Output Country Capital information for Country: = Range Countrycapitalmap {fmt. PRINTLN (Country, "capital is", Countrycapitalmap [country])}//See if the element exists in the collection captial, OK: = countrycapitalmap["US"]// Is true, it exists, otherwise there is no if (OK) {FMT. Println ("The capital of the United States is", captial)} else {fmt. Println ("The capital of the United States does not exist")}}func Deletemap () {//create map Countrycapitalmap: = map[string]string{"France": "Paris", "Italy": " Rome "," Japan ":" Tokyo "," India ":" New Delhi "} fmt. Println ("original map")//print map for Country: = Range Countrycapitalmap {fmt. PRINTLN (Country, "capital is", Countrycapitalmap [country])}//remove element Delete (Countrycapitalmap, "France") fmt. Println("French entries are deleted") fmt. Println ("delete element after map")//print map for Country: = Range Countrycapitalmap {fmt. PRINTLN (Country, "capital is", Countrycapitalmap [country])}}func main () {Mapdemo () Deletemap ()}
Four, go language Range1, Range introduction

The range keyword in the go language is used for elements of an iterative array (array), slice (slice), channels (channel), or collection (map) in a for loop. In arrays and slices, range returns the index of the element and the value corresponding to the index, and returns the key value of the Key-value pair in the collection.

2. Rang Use example
package mainimport "fmt"func rangeDemo(){   //使用range遍历切片   nums := []int{2, 3, 4}   sum := 0   //返回的切片的索引可以省略   for _, num := range nums {      sum += num   }   fmt.Println("sum:", sum)   //在切片上使用range,返回index和值   for i, num := range nums {      if num == 3 {         fmt.Println("index:", i)      }   }   fmt.Println(sum)   //使用range迭代map   kvs := map[string]string{"a": "apple", "b": "banana"}   for k, v := range kvs {      fmt.Printf("%s -> %s\n", k, v)   }   //使用range遍历Unicode字符串,返回字符的索引与字符(Unicode的值)本身   for i, c := range "go" {      fmt.Println(i, c)   }}func main() {   rangeDemo()   a := map[int]string{1:"hello",2:"world"}   for k,v := range a{   fmt.Println(k,v)}}

Go language Development (iii), go language built-in container

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.