Go language Learning-arrays-slicing-map

Source: Internet
Author: User
Tags array length

Array

Features of the array in the Go language:

The length of the array is fixed, and the length is part of the array type
is a value type that, when assigned or passed as a parameter, copies the entire array, not the pointer
To define the syntax for an array:

var arr1 = [5]int{1,2}          // [5]int{1, 2, 0, 0, 0}  未初始化的值,就默认初始化为该类型的默认值var arr2 = [...]int{1,2,3}      // [3]int{1,2,3}  长度可由初始化的元素个数确定var arr3 = [5]int{1: 20, 4: 50}  // 可使用索引来初始化,其他值仍然是对应类型的默认值var arr4 = [2][3]int{{1,2,3}, {2,3,4}}  // 多维数组
Array common operations access to array elements

can be accessed directly using indexed values

Iterating through an array
var arr = [5]string{"hello", "a", "b", "world", "sss"}// 这里只接收一个值,那这个值就是索引值for i := range arr {    fmt.Println(arr[i]);}// 接收两个值,就分别是索引值 和 索引对应的数组值for i, v := range arr {    fmt.Println(i, v);}

Both the Len and the CAP methods can return the array length, which is the number of elements

Slice-Slicing

The bottom of the slice is an array, which references the array fragments through internal pointers and some related properties, so slice can be long.

Structure of the Slice:

struct Slice {    byte* array;    uintgo len;    uintgo cap;}

Features of sliced slice:

    • The reference type is itself a struct.
    • Property Len indicates the number of elements stored internally
    • CAP indicates the capacity of the current slice
    • If the attribute slice = = Nil, then Len, Cap should be 0
    • Slices can be generated by an array, or they can be created directly, or read and written to a slice, which is essentially an array of operations underlying
// 通过数组产出切片var arr = [8]int{2,3,5,7,4,6,9,10}var s1 = arr[1:5:6]    // 语法 [start: end: max], 此时 len = end - start, cap = max-start// 直接创建切片var s2 = []int{2,4,7}  // 注意这里声明的是切片,"[]"没有数字,go会自动分配底层数组// 使用make动态创建切片var s3 = make([]int, 6, 8)   // 语法: make([]类型, len, cap); 可以省略cap,此时cap = len// 通过切片创建新切片, 新切片仍然执行原数组var s4 = s1[1,2,3]    // 与从数组产生切片是相似的,不过要注意范围
Common operations for slices
func append([]T, t …T) []T

As can be seen from the signature of the function, the function is to add elements to the end of the slice, you can add multiple values at a time, return new slices,
If the original Slice.cap limit is exceeded, the underlying array is reassigned, even if the original array is not filled.

s5 := append(s4, 20)
func copy(dst, src []T) int

This method copies a slice of type T from the source address SRC to the destination address DST, overwriting the relevant elements of DST, and returns the number of elements copied.
The source address and destination address may overlap. The number of copies is the minimum length of SRC and DST.

It depends on the example.

src := []int{1,2,3,4}dst := []int{2,3,4}num := copy(dst, src)  // dst=[]int{1,2,3}, num=3src2 := []int{1,2,3}dst2 := [2,3,4,5]num2 := copy(dst2, src2)  // dst2=[]int{1,2,3,5}, num2=3src3 := []int{1,2,4}dst3 := []int{1,2,3,5}   num3 := copy(dst3, src3)   // dst3=[]int{1,2,4,5} num3=3

The Len () and Map () methods return the number of elements in the slice and the capacity of the slice, respectively

Map type

The map type is a data structure called a hash table, called a dictionary in Python, also known as an associative array. It is a set of unordered key-value pairs. The given key can quickly locate the corresponding value

Characteristics:

    • Reference type
    • The key must be a type that supports equality comparison (= = =), for example: number,string,array,struct, etc.
    • Value can be of any type
    • It can be dynamically scaled and there are no restrictions

Definition syntax:

map[keyType]valueType{    key1: value1,    key2: value2,    ...    }// eg:m := map[string]int{    "age": 10,    "month": 12,    "day": 7,    "num": 1,    // 这里最后一行必须加上逗号,要不然,就把 "}"放在这个一行}

You can also use the Make function to define a map to help improve performance. Because of prior application?? Block memory to avoid frequent expansion during subsequent operations.

Grammar:

// 这里的 length 是map的初始容量,可以不加,不过在添加元素时会平凡扩张,影响性能make(map[keyType][valueType][, length])
The basic operation of the map type accesses the values in the map

You can use Map[key] to access the corresponding values directly

eg

var m = map[int]string{    1: "hello",    2: "world",    5: "你好",}// 迭代mapfor k := range m {    fmt.Println(m[k]);} // 还可以直接获得键和值for k, v := range m {    fmt.Println(k, v)}
Test key is present

We'll use it a lot of times.

// 这里使用了初始化,如果key存在, ok就是true, _接收的第一的参数就是值// 如果key不存在,ok就是falseif _, ok := m[key]; ok {    //...}
Deletes the specified key-value pair

Delete the key before you can also determine whether the key exists, if the key does not exist will be an error

var m = map[int]string{    1: "hello",    2: "world",    5: "你好",}delete(m, 1)  // 删除键为1的键值对

Go language Learning-arrays-slicing-map

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.