標籤:
定義一些變數,並輸出其地址
一、一般變數
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:關於變數地址的疑惑