go:關於變數地址的疑惑

來源:互聯網
上載者:User

標籤:

 

定義一些變數,並輸出其地址

一、一般變數

var a, b int32var c, d int64

輸出其地址

結果:

a 0xc082006310
b0xc082006320
c0xc082006330
d0xc082006340

結論:

  它們的地址間隔均為16位元組,其它空餘的地址浪費了?

 

二、數組切片

e := make([]byte, 40)f := make([]byte, 40)g := make([]byte, 40)f = []byte("12345678901234567890")                     //字串長度為20位元組g = []byte("1234567890123456789012345678901234567890") //字串長度為40位元組

1.輸出各自len()與cap()

結果:

e:  40  40

f:  20  40

g:  40  40

結論:

  a.切片的實際長度len()與其資料的長度相關,f[30]是不可訪問的;

  b.make([]byte,40)只保證其最大容量為40,即cap()=40。

 

2.輸出首地址及其首個元素地址:

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])

結果:

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

結論:

  a.順序聲明切片變數時,它們的地址是"連續"的,分別間隔32位元組;

  b.切片的資料地址與切片本身的地址無關 

3.對於以下代碼:

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

t.data=buf 意味著什嗎?

 

1)輸出a和b的某些地址:

a := []byte("1234567890")b := new(test)b.set(a)

結果:

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

 

2)輸出a和b.data的len()和cap()

結果:

a:    10  16

b.data:  10  16

結論:

   &a[0]==&b.data[0],且兩者的資料和容量均相同,所以推測t.data=buf 意味著t.data和buf指向同一段資料 

  

  

  

  

  

  

go:關於變數地址的疑惑

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.