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指向同一段数据 

相关文章
相关标签/搜索