doulachan8217 2014-04-25 10:45
浏览 68
已采纳

如何在Go中分配非恒定大小的数组

How do you allocate an array in Go with a run-time size?

The following code is illegal:

 n := 1
 var a [n]int

you get the message prog.go:12: invalid array bound n (or similar), whereas this works fine:

 const n = 1
 var a [n]int

The trouble is, I might not know the size of the array I want until run-time.

(By the way, I first looked in the question How to implement resizable arrays in Go for an answer, but that is a different question.)

  • 写回答

1条回答 默认 最新

  • duan0821 2014-04-25 10:45
    关注

    The answer is you don't allocate an array directly, you get Go to allocate one for you when creating a slice.

    The built-in function make([]T, length, capacity) creates a slice and the array behind it, and there is no (silly) compile-time-constant-restriction on the values of length and capacity. As it says in the Go language specification:

    A slice created with make always allocates a new, hidden array to which the returned slice value refers.

    So we can write:

     n := 12
     s := make([]int, n, 2*n)
    

    and have an array allocated size 2*n, with s a slice initialised to be the first half of it.

    I'm not sure why Go doesn't allocate the array [n]int directly, given that you can do it indirectly, but the answer is clear: "In Go, use slices rather than arrays (most of the time)."

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?