Use of slice in Go

Source: Internet
Author: User

Code_013_slice_usage Project Main.gopackage mainimport ("FMT") func test (s []int) {S[0] =-1 fmt. Println ("Test:") for I, V: = range S {fmt. Printf ("s[%d]=%d\n", I, V)} FMT. Println ("\ n")}func main () {//var S1 []int//s2: = []int//var s3 []int = make ([]int, 0)//S4: =make ([]int, 0, 0) s: = []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9} s1: = S[2:5] FMT. Println (S1) s2: = S1[2:6] s2[3] = FMT. PRINTLN (S2) fmt. PRINTLN (s)///built-in functions using//1) Append function adds data to slice tail, returns new Slice object var ss []int SS = Append (ss, 1) SS = Append (ss, 2, 3) SS = Appen D (SS, 4, 5, 6) fmt. PRINTLN (ss) SS2: = Make ([]int, 5) SS2 = Append (SS2, 6) fmt. Println (SS2) SS3: = []int{1, 2, 3} SS3 = Append (SS3, 4, 5) fmt. The Println (SS3)//append function intelligently increases the capacity of the underlying array once it exceeds the original underlying array capacity//normally re-allocates the underlying array at twice-fold capacity and copies the original data sss: = Make ([]int, 0, 1) c: = Cap (SSS) for I: = 0; I < 50; i++ {sss = append (sss, i) if n: = Cap (SSS); n > C {fmt. Printf ("cap:%d-%d\n", C, n) c = n}}//copy//function copy assigns data between two slice//assignment length to Len Small, two silce can point to the same underlying array data: = [...] Int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9} v1: = data[8:]//{8, 9} v2: = Data[:5]//{0, 1, 2, 3, 4} copy (v2, v1)//DST:S2, Src:s1 FMT. Println (v2)//[8 9 2 3 4] FMT. PRINTLN (data)//[8 9 2 3 4 5 6 7 8 9]//slice do function parameters slice: = []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9} test (slice) fmt. Println ("main:") for I, V: = Range Slice {fmt. Printf ("slice[%d]=%d\n", I, V)}//Note: The value of the underlying array has been changed. Fmt. Println ("\ n")}

Use of slice in go

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.