Golang Slice split and append copy or reference

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

1.

slice1:= Slice[0:2]

References, not duplicates, so any modifications to Slice1 or slice will affect each other.

Data: = []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 0}data1: = data[0:2]data1[0] = 99fmt. Println (data1) fmt. PRINTLN (data)

[99 2]

[99 2 3 4 5 6 7 8 9 0]


2.Append

Append more Special

Statement:

SOURCE slice= src

Add slice = App

Result Slice=tar

1) If Len (src) + len (APP) <= cap (SRC) src and tar are pointing to the same data reference, i.e. modifying src or tar, will affect each other

2) Otherwise tar is a copy of the way src + app, ie modify SRC or tar, does not affect each other

In either case, the app will not be affected because the app will go to tar using copy

Func test2 () {Data: = make ([]int, Ten,] data[0] = 1data[1] = 2dataappend: = Make ([]int, ten, +)//len <=10 then result[0] = 99 will affect source slicedataappend[0] = 1dataappend[1] = 2result: = Append (data, dataappend ...) Result[0] = 99result[11] = 98fmt. Println ("Length:", Len (Data), ":", data) fmt. Println ("Length:", Len (Result), ":", result) fmt. Println ("Length:", Len (Dataappend), ":", Dataappend)}




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.