zoukankan      html  css  js  c++  java
  • go:关于变量地址的疑惑

    定义一些变量,并输出其地址

    一、一般变量

    var a, b int32
    var c, d int64

    输出其地址

    结果:

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

    结论:

      它们的地址间隔均为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 = 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指向同一段数据 

      

      

      

      

      

      

  • 相关阅读:
    套接字的工作流程
    信安系统设计基础(个人报告阅读说明)
    1.1Linux 系统简介(学习过程)
    1.12Linux下软件安装(学习过程)
    作业3.5
    作业1
    变量与基本数据类型
    python入门
    计算机基础知识补充
    计算机基础
  • 原文地址:https://www.cnblogs.com/xiaopipi/p/4966932.html
Copyright © 2011-2022 走看看