dsqtl335227 2011-08-16 19:07
浏览 64
已采纳

为什么切片长度大于容量长度会导致运行时错误?

Made a slice where capacity is less than the length


    package main

    import fmt "fmt"

    func main(){

     type b []int
     var k = make([]b, 10, 5)
     fmt.Printf("%d
",k[8])
     }

This when tried to run gives following error.


    panic: runtime error: makeslice: cap out of range

    runtime.panic+0x9e /go/src/pkg/runtime/proc.c:1060
            runtime.panic(0x453b00, 0x30020390)
    runtime.panicstring+0x94 /go/src/pkg/runtime/runtime.c:116
            runtime.panicstring(0x4afd6c, 0x40d80c)
    runtime.makeslice+0x70 /go/src/pkg/runtime/slice.c:24
            runtime.makeslice(0x44302c, 0xa, 0x0, 0x5, 0x0, ...)
    main.main+0x45 C:/GOEXCE~1/basics/DATATY~1/slice.go:8
            main.main()
    runtime.mainstart+0xf 386/asm.s:93
            runtime.mainstart()
    runtime.goexit /go/src/pkg/runtime/proc.c:178
            runtime.goexit()
    ----- goroutine created by -----
    _rt0_386+0xbf 386/asm.s:80

My question is can capacity be less than length?

If 'Yes' then why this error came?
And if 'No'then why this is a runtime error and why not a compile time?

  • 写回答

2条回答 默认 最新

  • dpxua26604 2011-08-16 20:10
    关注

    No, capacity cannot be less than length.

    A slice is a reference to a part of an array. A slice's capacity represents the size of that backing array. If its length is greater than its capacity, then what memory is it using?

    The following invariant always holds for a slice s (unless you've done something unsafe):

    0 <= len(s) <= cap(s)
    

    Your code produces a runtime error rather than a compile-time error because the error cannot always be detected statically. In your case it could be, but consider this code:

    package main
    
    import (
        "fmt"
        "rand"
    )
    
    func main() {
        k := make([]int, rand.Int(), rand.Int())
        fmt.Println(k)
    }
    

    The values passed to make cannot be known until runtime.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度