Golang Arrays and slices

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

Array

Declaring an array

Arrays are also declared in an inverted manner, and the array length needs to be specified when declaring an array. So declaring an array is [数组长度]类型 a way to declare it, and you can add an initialization list if you need to initialize it at the same time as the declaration {} .

//声明数组var array1 [2]intarray1[0] = 1array1[1] = 2fmt.Println(array1)//声明的同时初始化array2 := [3]int{1, 2, 3}fmt.Println(array2)

Once an array is declared, the length is fixed and immutable.

accessing arrays

This is relatively simple, as is the case with general programming languages. Here is a small example.

//访问数组numbers := [10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}for i := 0; i < len(numbers); i++ {    fmt.Print(numbers[i])}fmt.Println()

Slice

Although arrays are an important tool, they are sometimes less useful because they are fixed in length. Golang provides another powerful tool-slicing. Therefore, slicing is more commonly used in actual coding.

declaring slices

Slices are similar in type and array, except that slices cannot specify numbers inside square brackets. If you print slices, the results and arrays are similar.

array := [7]int{1, 2, 3, 4, 5, 6, 6}var numbers []int = array[:]fmt.Println(numbers)

Slices and arrays are the same in many places, but remember that slices are just a view, and changes to slices are reflected on the underlying array. If you modify the source array, the slices also reflect the modifications.

array[6] = 7fmt.Println(numbers)

If you only need to use slices, you can also not declare the underlying array, directly using the slice literal, which []类型{初始化列表} is the form.

numbers2 := []int{1, 2, 3, 4, 5}fmt.Println(numbers2)

Slice properties

Slices have two important properties, length and capacity . Length refers to the number of elements the slice contains, and the capacity refers to the length of the underlying array corresponding to the slice. Golang has two built-in functions to calculate the length and capacity of a slice.

fmt.Printf("长度:%d, 容量:%d", len(numbers), cap(numbers))

The default value of a slice is nil that the nil value slice has a length and capacity of 0, and there is no underlying array.

Slicing operations

If you know the language of Python, you should be familiar with slicing operations. In the go language, slice operations are similar.

First look at the subscript of the slice. The slice subscript can be ignored, and the corresponding lower bidding clubs extends to the end of the corresponding slice when it is ignored. For example, for a slice with 5 elements,,, a a[0:5] a[0:] a[:5] and a[:] both are equivalent, referring to the entire slice.

Golang has a built-in function make that helps us quickly create a slice, whose first parameter is the slice type, the second parameter is the length, and the third parameter is the capacity.

numbers3 := make([]int, 5, 10)fmt.Printf("长度:%d, 容量:%d\n", len(numbers3), cap(numbers3))

If you want to append an element to a slice, using the built-in function append , this function returns the slice after the append. If the slice has insufficient capacity to hold all the elements, Golang automatically assigns the new underlying array and returns the corresponding slice.

numbers = append(numbers, 8, 9, 10)fmt.Println(numbers)

Iteration

The Golang has an iterative keyword that you can use to iterate over slices and maps. When you use it to iterate over slices, the subscript and element values of the corresponding elements of the slice are returned, and if you write only one value, the subscript is iterated. The following example takes advantage of these two features, fills a slice first, and then prints its elements.

numbers := make([]int, 3)for i := range numbers {    numbers[i] = i}fmt.Println(numbers)for i, v := range numbers {    fmt.Printf("numbers[%d]=%d\n", i, v)}fmt.Println()

If you want to ignore one of the subscripts and values, you can use an _ underscore instead.

for _, value := range numbers {...}
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.