为什么你不能把一个变量作为一个多维数组大小放在Go中?

问题描述:

最近,我一直对机器学习感兴趣,特别是机器学习与图像,但要做到这一点,我需要能够处理图像。我希望对图像处理库的工作方式有更全面的了解,所以我决定建立自己的图书馆来阅读我能理解的图像。但是,我似乎有一个问题,当谈到读取图像的SIZE,因为这个错误弹出,当我尝试编译:为什么你不能把一个变量作为一个多维数组大小放在Go中?

./imageProcessing.go:33:11: non-constant array bound Size 

这是我的代码:

package main 

import (
// "fmt" 
// "os" 
) 

// This function reads a dimension of an image you would use it like readImageDimension("IMAGENAME.PNG", "HEIGHT") 

func readImageDimension(path string, which string) int{ 

var dimensionyes int 

if(which == "" || which == " "){ 
    panic ("You have not entered which dimension you want to have.") 
} else if (which == "Height" || which == "HEIGHT" || which == "height" || which == "h" || which =="H"){ 
    //TODO: Insert code for reading the Height of the image 

    return dimensionyes 

} else if (which == "Width" || which == "WIDTH" || which == "width" || which == "w" || which =="W"){ 
    //TODO: Insert code for reading the Width of the image 

    return dimensionyes 

} else { 
    panic("Dimension type not recognized.") 
    } 
} 

func addImage(path string, image string, Height int, Width int){ 
    var Size int 
    Size = Width * Height 
    var Pix [Size][3]int 
} 

func main() { 


} 

我刚刚开始用Go编程,所以如果这个问题听起来不怎么样,我很抱歉

因为Go是一种静态类型语言,这意味着变量类型需要在编译时知道。

Go中的Arrays是固定大小:一旦您在Go中创建数组,您将无法在以后更改其大小。这是因为数组的长度是数组类型的一部分(这意味着类型[2]int[3]int是2个不同的类型)。

变量的值在编译时通常是不知道的,所以使用它作为数组的长度,编译时就不会知道类型,因此它是不允许的。

阅读相关的问题:How do I find the size of the array in go

如果你不知道在编译时的大小,使用slices代替阵列(还有其他原因可以使用切片太)。

例如这样的代码:

func addImage(path string, image string, Height int, Width int){ 
    var Size int 
    Size = Width * Height 
    var Pix [Size][3]int 
    // use Pix 
} 

可以转化创建和使用这样的片:

func addImage(path string, image string, Height int, Width int){ 
    var Size int 
    Size = Width * Height 
    var Pix = make([][3]int, Size) 
    // use Pix 
}