为什么切片长度大于容量长度会导致运行时错误? [英] Why slice length greater than capacity gives runtime error?

查看:127
本文介绍了为什么切片长度大于容量长度会导致运行时错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

制作一个容量小于长度的切片

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\n",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?

推荐答案

否,容量不能小于长度.

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?

以下不变式对于切片s总是成立的(除非您做了不安全的操作):

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)
}

传递给make的值要到运行时才能知道.

The values passed to make cannot be known until runtime.

这篇关于为什么切片长度大于容量长度会导致运行时错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆