为什么不能在Go中将变量作为多维数组大小?

时间:2017-10-18 11:50:49

标签: arrays image-processing go computer-vision

最近,我对机器学习更感兴趣,机器学习图像,但要做到这一点,我需要能够处理图像。我想更全面地了解图像处理库如何工作,所以我决定创建自己的库来阅读我能理解的图像。但是,在阅读图像的 SIZE 时,我似乎遇到了一个问题,因为当我尝试编译时会弹出这个错误:

 ./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编程,所以如果这个问题听起来不错,我很抱歉

1 个答案:

答案 0 :(得分:6)

因为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
}