Go language Basics: make,new, Len, Cap, append, delete method

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

There are a lot of Go's built-in functions mentioned earlier, and this article learns how to use it.

Make

First take make surgery, but at the beginning I went into the misunderstanding, because I want to find his source, first found that Src/builtin/builtin.go has func make (type, size Integertype) Type, but there are only two parameters, As I know the make is a variable parameter, so I continue to search the source package is also the other made function prototype declaration, but all in vain.
So look for Niang, a bit of information is not. or Google Bar, find a bunch of English explanations, found two Web site explanation can also, specifically see how can the Golang makes function can take three parameters? and Golang builtin package.
The general meaning is I found in the source builtin.go is just a document, not the source code, these functions are specially processed, we can not directly to use them. Compared to make, the real implementation is in the runtime package inside the Makeslice, specifically how to do, it is necessary to study the compiler, see how the assembly is implemented.
Alas, the source of light make is tossing my day, the brain is not enough to use Ah, who lent me a head so.
Good, to here, although did not find make the specific source code, but know make is no direct specific source, forget.
Make can only allocate memory and initialize for slice, MA p, or channel types, and return a slice, map, or channel type reference with an initial value, not a pointer. Specifically how to use make, the official website of Https://golang.org/ref/spec#Making_slices_maps_and_channels has introduced, here directly paste out:

PagerTypeT Resultmake (t, n) Slice Slice of typeT withLength n andCapacity nmake (T, N, m) Slice slice of typeT withLength n andCapacity Mmake (T)Map        Map  of typeTmake (T, N)Map        Map  of typeT withInitial space forn Elementsmake (T) channel unbuffered Channel of typeTmake (T, n) channel buffered channel of typeTBufferSize n

Example:

 PackageMainImport "FMT"funcMain () {Slice1: = Make([]int,5) Slice2: = Make([]int,5,Ten) FMT. Println (Slice1,Len(Slice1),Cap(Slice1)) Fmt. Println (Slice2,Len(Slice1),Cap(SLICE2)) MAP1: = Make(Map[string]int) Map2: = Make(Map[string]int,5) FMT. Println (MAP1,Len(MAP1)) Fmt. Println (MAP2,Len(MAP2))}

Output:

[0 0 0 0 0] 5 5[0 0 0 0 0] 5 10map[] 0map[] 0

For make slice, there are two concepts to figure out: length and capacity.

    • The capacity represents the size of the underlying array, and the length is the size you can use.
    • Where is the capacity used? When you extend the length with the Appen D, if the new length is less than the capacity, the underlying array will not be replaced, otherwise go will apply a new underlying array, copy the value over here, and discard the original array. That is, the purpose of capacity is to provide a trade-off between the consumption of data copies and memory requests and the memory footprint.
    • And the length is to help you limit the number of members available to the slice, providing a boundary query. So when you use make to apply for a good space, you need to be careful not to cross the "Yue Len"

New

The exact prototype function that is not found, only has the Func new (Type) *type in Src/builtin/builtin.go. Based on the previous experience with the specific prototype of make, I guess this is the new function format, and the call should be similar to the Func newint () *int function, which should still be done by the compiler link.
But we use new allocated space, and the function returns a pointer to the newly assigned 0 value. The function is formatted as follows:

new(Type) *Type

Example

    new([2]int)    fmt.Println(new1)    new1[01    new1[12    fmt.Println(new1)

Output:

&[0 0]&[1 2]

Len and Cap

function len Format:

funclenint
    • If V is an array: Returns the number of elements in the array
    • If V is a pointer to an array: the number of elements returned is *V
    • If V is slice or map: Returns the number of elements of V
    • If V is channel:the number of elements queued (unread) in the channel buffer; it's not clear what the channel is, just move it over the Internet.

Format of the function Cap:

funccapint
    • Array: Returns the number of elements in the array, with Len (v)
    • Pointer to array: Returns the number of elements of *v, with Len (v)
    • Slice: Slice maximum capacity is returned, >=len (v)
    • Channel:the channel buffer capacity, in units of element

Append

Append appends the element to the end of the slice slice, and if it has sufficient capacity, its target is re-sliced to accommodate the new element. Otherwise, a new base array is assigned. Append returns the updated slice, so the appended result must be stored.

There are two ways to use append:

slice = append(slice, elem1, elem2)slice = append(slice, anotherSlice…)

In the first usage, the first argument is slice, and you can add multiple parameters later.
If you are stitching together two slice, you will need to use the second one, add three points after the name of the second slice, and this time append only supports two parameters and does not support any number of arguments.
Personal feeling Method 2 used more
Example 1 "Using Method 1":

make([]int, 5, 10append(slice2, 5, 6, 7, 8, 9lencapappend(slice2, 10lencap

Output:

[0 1 2 3 4 5 6 7 8 9] 10 10[0 1 2 3 4 5 6 7 8 9 10] 11 20//注意容量变为了20

Example 2 "Using Method 1":

    d := []string{"Welcome""for""Hangzhou, ""Have""a""good""journey!"}    insertSlice := []string{"It""is""a""big""city, "}    3    d = append(d[:insertSliceIndex], append(insertSlice, d[insertSliceIndex:]...)...)    fmt.Println(d)

Output:

[Welcome for Hangzhou,  It is a big city,  Have a good journey!]

Delete

The built-in function delete removes the element from the map by the specified key. If M is nil or does not have this element, delete does not operate.
Function structure:

map[TypeType)

Example

    make(map[string]int)    map1["one"] = 1    map1["two"] = 2    map1["three"] = 3    map1["four"] = 4    len(map1))    delete"two")    len(map1))

Output:

map[three:3four:4one:1two:24map[four:4one:1three:33//map 是无序的,每次打印出来的 map 都会不一样,所以它不能通过 index 获取,而必须通过 key 获取

Basically, the functions we encountered earlier have a simple explanation here.

Reference:

Https://wizardforcel.gitbooks.io/golang-stdlib-ref/content/6.html#make
https://golang.org/ Ref/spec#making_slices_maps_and_channels
Http://www.oschina.net/translate/go-lang-slices

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.