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 linux驱动,linux应用,多线程
  • ¥20 我要一个分身加定位两个功能的安卓app
  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助