Golang--slicing

Source: Internet
Author: User
Tags printf
slices

The slice (slice) itself is not a dynamic array or an array pointer. It internally sets the action to the specified array by referencing the underlying array and setting the correlation property.
There are three properties: the underlying array pointer, length, capacity.
Length refers to the length of the current slice, which is the length at which the underlying array has been stored.
Capacity is the maximum length that a slice can use, not necessarily the length of the underlying array. Defining and initializing

Slices can be obtained from existing arrays, or they can be created directly.
Because a slice is a reference type, the underlying array is not assigned when created directly, so memory allocation is done using the Make function or the display initialization statement.

Package main

Import (
    "FMT"
)

func main () {

    arr: = [...] Int{1, 2, 3}  //array
    SLC: = arr[:]  //slice with arr array created for the underlying array

    slc_a: = []int{1, 2, 3}  //slice (display initialization)
    SLC _b: = Make ([]int, 3, 4)  //  slice (make function)

    FMT. Printf ("%t\n", SLC)
    FMT. Printf ("%t\n", slc_a)
    FMT. Printf ("%t\n", Slc_b)

}

Make function Signature: Func make (type, size Integertype) Type
The slice's capacity is greater than or equal to the length.

Package main

Import (
    "FMT"
)

func main () {
    SLC: = Make ([]int, 3, 4)  //Length 3 Volume 4
    //SLC: = Make ([]int, 3)  Length 3 Volume 3
    fmt. Printf ("Slice len =%d, Cap =%d\n", Len (SLC), Cap (SLC))
}

Slice is a reference type, and initialization is nil.

Package main

Import (
    "FMT"
)

func main () {
    var SLC []int/  /define only
    B: = []int{}  / /define simultaneous initialization of

    FMT. PRINTLN (SLC = = nil)
    FMT. Println (b = = nil)
}

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.