Make parameters (for pits)

Source: Internet
Author: User

The third parameter of Golang make ()


Study for a period of time Golang, probably can use Golang to do some small things, so review some of the basic things. Golang allocated memory has a make function, the first parameter of the function is the type, the second argument is the allocated space, the third parameter is the reserved allocation space, the first two parameters are well understood, but I have a face to the third parameter, such as A:=make ([]int, 5, ten), Len (a) The output is 5,cap (a) output is 10, and then I to a[4] assignment found is can get, but to a[5] to assign value found error, so depressed this reserve allocated space how to use it, so Google a bit to find that the original reserved space needs to be re-sliced to use, So make a record, the code is as follows.

Packagemain

Import "FMT"

Funcmain () {

A: =make ([]int,10,20)

Fmt. Printf ("%d,%d\n", Len (a), Cap (a))

Fmt. Println (a)

B: = A[:cap (a)]

Fmt. Println (b)

}

Output results

10,20

[0 0 0 0 0 0 0 0 0 0]

[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]


Problem resolution for value passing in for loop


Problem Description:

Iterate through an array and modify the values in them:

Package Main

Import (

"FMT"

)

Type Link struct {

a int

}

Func Main () {

Arr: = Make ([]link, 10)

For I, V: = Range arr {

V.A = i

}

For _, V: = Range arr {

Fmt. Println (V.A)

}

}

Expected output, all V.A in the array are modified to the values in I

Actual output, none of the V.A in the array has changed

Problem analysis

In the Go For...range loop, go always uses the value copy instead of the traversed element itself, simply, that value in For...range is a duplicate value copy , not the element itself. A property cannot be modified by & (address).

Solution: Directly call an array

Package Main

Import (

"FMT"

)

Type Link struct {

a int

}

Func Main () {

Arr: = Make ([]link, 10)

For I, _: = Range Arr {

ARR[I].A = i

}

For _, V: = Range arr {

Fmt. Println (V.A)

}

}

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.