英文:
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 "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])
}
}
答案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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论