Go data Type (cont.)-array, slice, map

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

Go implements common data structure arrays (array), slices (slice), and maps (map) as built-in types. You can use array to sort multiple values in a list, or use more flexible: slice. A dictionary or hash type can also be used, which is called map in Go.

1. Array

  • Array definition

    Array definition [n]<type> , n is an array length, the length is a part of the type, cannot be changed after the definition of the size of the arrays; <type> [ ]

    var arr [10]int// 定义长度为 10 的整型数组arr[015// 赋值arr[933ib := arr[0// 读取
  • Array initialization

    In the Go fix, the declared variable is not initialized and is assigned the default value of 0 of its type. arrays, the uninitialized array is automatically assigned a value of 0. The initialization of an array can be done using the curly brace value at the time of declaration, and if each element is given an initial value, you can omit the size use ... instead, and the compiler automatically calculates the size of the array.

    varA0[Ten]int //initialized to 0A: =[3]int{1,2,4}//Declaration and initialization of the session//equivalent to A: = [...] Int{1, 2, 4}/ * Multidimensional array * /B: =[2][2]int{[2]int{1,2},[2]int{3,4} }//equivalent to B: = [2][2]int{[...] Int{1, 2}, [...] Int{3, 4}}The following simpler form can be used in the new version after 2010-10-27B: =[2][2]int{{1,2},{3,4}}

Note : Arrays are value types: assigning an array to another array copies all of the elements. Especially when passing an array to a function , it gets a copy of the array , not the pointer to the array .

2, Slice

The slice is close to the array, but can increase the length when new elements are added. Slice always points to an array at the bottom. Slice is a pointer to an array, which is different from the array; Slice is a reference type, which means that when you assign a slice to another variable, two references point to the same array. If a function requires a slice parameter, modifications to the slice element in it will also be reflected in the function caller, similar to passing the underlying array pointer.

  • Slice Create

    Slice can be created using built-in functions. It always appears in pairs with a fixed-length array. There is no difference between the slice and the underlying array.

    SL: = Make([]int,Ten)//Create a slice that holds 10 elementsvararr [M]int //Create an array, assuming M > 4Slice: = Arr[0: n]//Create a slice to this array, length n, index: 0 ~ n-1/* Length and capacity */Len(slice) = = NCap(slice) = = mLen(arr) = =Cap(arr) = = m/ * Select a certain interval element to create slice * /SL1: = arr[1: 5]//Index is 1 ~ 4SL2: = arr[: 5]//Index is 0 ~ 4SL3: = arr[2:]//Index is 2 ~ m-1SL4: = arr[:]//Index is 0 ~ m-1

    Given an array or other slice, a new slice a[i:j] is created by the way. This creates a new slice, pointing to variable A, indexed to i~ j-1 (half closed half-open interval). Length is j-i. Omit I the default index starts at 0, omit J The default index ends at the last element of the array, and both I and J omit the slice to take the entire array of elements. Neither I nor J can exceed the range of the array index, or a run-time error will occur.

  • Extended Slice

    Extended slice can use the built-in functions append and copy.
    Description from the document:
    The function append appends a value of 0 or other X to slice S, and returns the new appended, slice with the same type as S. If s does not have enough capacity to store the appended value, append allocates a large enough, new slice to hold the original slice element and the appended value. Therefore, the returned slice may point to a different underlying array.

    s0 := []int{0, 0append(s0, 2// 追加一个元素append(s1, 3, 5, 7// 追加三个元素append// 追加一个 slice,**注意此处的三个点**

    The function copy copies elements from the source slice src to the target DST, and returns the number of copied elements. Sources and targets may overlap. The number of copies is the minimum value in Len (SRC) and Len (DST).

    var a = [...]int{0, 1, 2, 3, 4, 5, 6, 7}varmake([]int, 6copy(s, a[0// n1 == 6, s == []int{0, 1, 2, 3, 4, 5},多余的不复制copy(s, s[2// n2 == 4, s == []int{2, 3, 4, 5, 4, 5}

3. Map

Go maps the map as the built-in type. The format of the general definition map is:

map[<key type>]<value type>

For example, define a map that represents the number of days per month:

Monthdays: =Map[string]int{"Jan": to,"The Feb": -,"Mar": to,"APR": -,"may": to,"June": -,"Jul": to," the": to,"Sep": -,"OCT": to,"Nov": -,"Dec": to, ← comma is required}

When declaring only one map without initialization, you need to use built-in function make. Such as

make(map[string]int)

Access to the map is in the form of a square bracket plus key:

monthdays["Undecim"30// 添加一个元素monthdays["Feb"29// 修改值jan := monthdays["Jan"// 取键为 "Jan" 的值

To verify that a key exists in the map, you can use the comma OK form:

val, ok := monthdays["Jan"// 若键 "Jan" 存在,ok == true

Delete an element from the map, using the delete(map, key) .

delete"Mar"// 删除键为 "Mar" 的元素

4. Traversing array, slice, map

You can use range to iterate through an array, slice, string, or map, which returns a key and the corresponding value each time it is called.

// 计算一年的天数// 使用 range 对 map 进行遍历year := 0forrange// 键没有使用,因此用 _, days    year += days}

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.