go:關於變量地址的疑惑

 

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

1、通常變量spa

var a, b int32
var c, d int64

輸出其地址blog

結果:字符串

a 0xc082006310
b 0xc082006320
c 0xc082006330
d 0xc082006340class

結論:test

  它們的地址間隔均爲16字節,其它空餘的地址浪費了?變量

 

2、數組切片數據

e := make([]byte, 40)
f := make([]byte, 40)
g := make([]byte, 40)
f = []byte("12345678901234567890")                     //字符串長度爲20字節
g = []byte("1234567890123456789012345678901234567890") //字符串長度爲40字節

  

 

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

結果:make

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 = buf
	return
}

 

  

 

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指向同一段數據 

相關文章
相關標籤/搜索