如何在Go编程语言中为数组分配内存?

huangapple go评论210阅读模式
英文:

How do I allocate memory for an array in the go programming language?

问题

我想在Go语言中创建一个大小为N的数组,但我不知道N在编译时会是多少,我该如何为它分配内存?

例如:

  1. func MakeArray(size int) {
  2. return new ([size]int)
  3. }

这段代码不起作用,因为size不是一个常量。

这似乎是一个简单的问题,但我刚开始使用Go语言,从教程中(或者说从文档中搜索)并不明显如何做到这一点。

英文:

I want to make an array of size N in go, but I don't know what N will be at compile time, how would I allocate memory for it?

e.g.

  1. func MakeArray(size int) {
  2. return new ([size]int)
  3. }

which doesn't work since size is not a constant.

This seems like a simple question, but I just started using go and it's not obvious to me how to do this from reading the tutorial (or searching the documentation for that matter).

答案1

得分: 17

The function make creates slices, maps, and channels, and it returns an initialized value of type T. The make() call allocates a new, hidden array to which the returned slice value refers.

  1. package main
  2. import "fmt"
  3. func main(){
  4. ptr := new(int)
  5. *ptr = 100
  6. fmt.Println("*ptr = ", *ptr)
  7. slice := make([]int, 10) // slice with len(slice) == cap(slice) == 10
  8. for i:=0; i<len(slice); i++{
  9. fmt.Println(slice[i])
  10. }
  11. }
英文:

The function make creates slices, maps, and channels, and it returns an initialized value of type T. The make() call allocates a new, hidden array to which the returned slice value refers.

  1. package main
  2. import &quot;fmt&quot;
  3. func main(){
  4. ptr := new(int)
  5. *ptr = 100
  6. fmt.Println(&quot;*ptr = &quot;, *ptr)
  7. slice := make([]int, 10) // slice with len(slice) == cap(slice) == 10
  8. for i:=0; i&lt;len(slice); i++{
  9. fmt.Println(slice[i])
  10. }
  11. }

答案2

得分: 10

对于切片,Go语言的make内建函数有两个或三个参数。

  1. make(T, n) 长度为n,容量为n的类型为T的切片
  2. make(T, n, m) 长度为n,容量为m的类型为T的切片
英文:

For slices, the Go make built-in function has two or three arguments.

  1. make(T, n) slice of type T with length n and capacity n
  2. make(T, n, m) slice of type T with length n and capacity m

huangapple
  • 本文由 发表于 2011年6月25日 13:34:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/6476070.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定