Golang Slice and Array differences

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

Array type

is a fixed-length array that must be determined before using the array length array

golangarrayFeatures:

    • golangThe array in is 值类型 , that is, if you assign an array to another array, then the entire array is actually copied a copy of the
    • If golang the array in the function is an argument, the actual passed argument is a copy of the array, not the pointer to the array
    • arrayis also part of the length, which means it Type [10]int [20]int is not the same.

sliceType

    • sliceis a reference type and is a dynamic pointer to an array slice.
    • sliceis a variable-length data structure that always points to the underlying array array .

1. Create Slice

动态数组创建,类似创建数组,但是没有指定固定长度var al []int     //创建slicesl := make([]int,10)  //创建有10个元素的slicesl:=[]int{1,2,3} //创建有初始化元素的slice

2. Create the array first, and set up the slice based on the array slice

var arr =[10]{1,2,3,4,5。6}  sl := arr[2:5] //创建有3个元素的slice

3.slice has some easy-to-operate

 - `slice`的默认开始位置是0,`ar[:n]`等价于`ar[0:n]` - `slice`的第二个序列默认是数组的长度,`ar[n:]`等价于`ar[n:len(ar)]`

The difference between an array and a slice

    • When declaring an array, the length of the array is indicated in square brackets or ..., when the slice is declared, the square brackets are empty
    • As a function parameter, the array passes a copy of the array, and slice passes the pointer.

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.