doujugu1722 2019-07-18 01:31
浏览 136
已采纳

golang切片中哪种类型的大小为零?

which type's size is zero in slice of golang?

When I read the source code of golang slice, I found a code et.size == 0. so I want to know which type's size is 0?

func growslice(et *_type, old slice, cap int) slice {
    ...
    if et.size == 0 {
        if cap < old.cap {
            panic(errorString("growslice: cap out of range"))
        }

        return slice{unsafe.Pointer(&zerobase), old.len, cap}
    }
    ...
}
  • 写回答

1条回答 默认 最新

  • douxueke5653 2019-07-18 02:21
    关注

    The Go Programming Language Specification

    Size and alignment guarantees

    A struct or array type has size zero if it contains no fields (or elements, respectively) that have a size greater than zero. Two distinct zero-size variables may have the same address in memory.


    For example,

    package main
    
    import (
        "fmt"
        "unsafe"
    )
    
    func main() {
        type zero struct{}
        fmt.Println(unsafe.Sizeof(zero{}))
        slice := make([]zero, 7)
        fmt.Printf("%d %v %p %p
    ", len(slice), slice, &slice[0], &slice[len(slice)-1])
    }
    

    Playground: https://play.golang.org/p/pn8Rz0IorwD

    Output:

    0
    7 [{} {} {} {} {} {} {}] 0x1c4c84 0x1c4c84
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 宇视监控服务器无法登录
  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥50 power BI 从Mysql服务器导入数据,但连接进去后显示表无数据
  • ¥15 (关键词-阻抗匹配,HFSS,RFID标签天线)