Go: Doubts about the address of a variable

Source: Internet
Author: User

Define some variables and output their addresses

First, general variables

var A, b int32var C, D Int64

Output its address

Results:

A 0xc082006310
b0xc082006320
c0xc082006330
d0xc082006340

Conclusion:

They have an address interval of 16 bytes, and other spare addresses are wasted?

Second, array slicing

E: = Make ([]byte, max) F: = make ([]byte, max) G: = Make ([]byte, +) F = []byte ("12345678901234567890")                     //String length 20 bytes g = []by Te ("1234567890123456789012345678901234567890")//String length is 40 bytes

1. Output respective len () and Cap ()

Results:

E:40 40

F:20 40

G:40 40

Conclusion:

A. The actual length of the Slice Len () is related to the length of the data, f[30] is inaccessible;

B.make ([]byte,40) only guarantees a maximum capacity of 40, which is cap () = 40.

2. Output the first address and its first element address:

Fmt. Printf ("&e:%p &e[0]:%p", &e, &e[0]) fmt. Printf ("&f:%p &f[0]:%p", &f, &f[0]) fmt. Printf ("&g:%p &g[0]:%p", &g, &g[0])

Results:

&e:0xc082008660 &e[0]:0xc08204c060
&f:0xc082008680 &f[0]:0xc0820086c0
&g:0xc0820086a0 &g[0]:0xc08204c0f0

Conclusion:

A. When declaring tile variables sequentially, their addresses are "contiguous" and are spaced 32 bytes apart;

B. The data address of the slice is independent of the address of the slice itself

3. For the following code:

Type test struct {data []byte}func (T *test) set (buf []byte) {t.data = bufreturn}

What does the T.data=buf mean?

1) Some addresses for outputs A and B:

A: = []byte ("1234567890") B: = new (Test) B.set (a)

Results:

&a:0xc082002660
&a[0]: 0xc082004310
&b:0xc082028020
&b.data:0xc082002680
&b.data[0]: 0xc082004310

2) Len () and Cap () for output A and b.data

Results:

A:10 16

B.data:10 16

Conclusion:

&a[0]==&b.data[0], and both data and capacity are the same, so presumably t.data=buf means that t.data and buf point to the same piece of data 

  

  

  

  

  

  

Go: Doubts about the address of a variable

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.