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

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

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

问题

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

例如:

func MakeArray(size int) {
  return new ([size]int)
}

这段代码不起作用,因为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.

func MakeArray(size int) {
  return new ([size]int)
}

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.

package main

import "fmt"

func main(){

   ptr := new(int)
   *ptr = 100

   fmt.Println("*ptr = ", *ptr)

   slice := make([]int, 10)    // slice with len(slice) == cap(slice) == 10

   for i:=0; i<len(slice); i++{
      fmt.Println(slice[i])
   }
}
英文:

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.

package main

import &quot;fmt&quot;

func main(){

   ptr := new(int)
   *ptr = 100

   fmt.Println(&quot;*ptr = &quot;, *ptr)

   slice := make([]int, 10)    // slice with len(slice) == cap(slice) == 10

   for i:=0; i&lt;len(slice); i++{
      fmt.Println(slice[i])
   }
}

答案2

得分: 10

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

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

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

make(T, n)       slice of type T with length n and capacity n
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:

确定