go - 在 go 中使用 var 和不使用 var 声明变量的区别

标签 go indexoutofboundsexception

我在使用 step 35 in the tour of Go 时遇到了一些问题运动。

这是我的代码:

package main

import "code.google.com/p/go-tour/pic"

func Pic(dx, dy int) [][]uint8 {
    var pic = make([][]uint8, dy)
    for y := 0; y < dy; y++ {
        pic[y] = make([]uint8, dx)
        for x := 0; y < dx; x++ {
            pic[y][x] = uint8(x*y)
        } 
    }
    return pic
}

在寻找解决方案时,我找到了PeterSO's完美运行的代码

func main() {
    pic.Show(Pic)
}

func Pic(dx, dy int) [][]uint8 {
    pixels := make([][]uint8, dy)
    for y := 0; y < dy; y++ {
        pixels[y] = make([]uint8, dx)
        for x := 0; x < dx; x++ {
            pixels[y][x] = uint8(x * y)
        }
    }
    return pixels
}

我能看到的唯一区别是,我使用 var 关键字定义 pic 变量,而他的代码使用 :=赋值。现在,为什么我的代码不起作用?

最佳答案

你写的

for x := 0; y < dx; x++ {
    pic[y][x] = uint8(x * y)
}

特别是:y < dx ,这导致,

panic: runtime error: index out of range

我写了

    for x := 0; x < dx; x++ {
        pixels[y][x] = uint8(x * y)
    }

特别是:x < dx .因此,更改您的 yx .

package main

import "code.google.com/p/go-tour/pic"

func Pic(dx, dy int) [][]uint8 {
    var pic = make([][]uint8, dy)
    for y :=0; y < dy; y++ {
        pic[y] = make([]uint8, dx)
        for x :=0; x<dx; x++ {
            pic[y][x] = uint8(x*y)
        } 
    }
    return pic
}

func main() {
    pic.Show(Pic)
}

http://play.golang.org/p/UvGgszFhl-

go tour slices

Variable declarations

A variable declaration creates a variable, binds an identifier to it and gives it a type and optionally an initial value.

VarDecl     = "var" ( VarSpec | "(" { VarSpec ";" } ")" ) .
VarSpec     = IdentifierList ( Type [ "=" ExpressionList ] | "=" ExpressionList ) .

Short variable declarations

A short variable declaration uses the syntax:

ShortVarDecl = IdentifierList ":=" ExpressionList .

It is a shorthand for a regular variable declaration with initializer expressions but no types:

"var" IdentifierList = ExpressionList .

Unlike regular variable declarations, a short variable declaration may redeclare variables provided they were originally declared earlier in the same block with the same type, and at least one of the non-blank variables is new.

在您的代码中 var pic = make([][]uint8, dy)和简称 pic := make([][]uint8, dy)两者都会起作用。

关于go - 在 go 中使用 var 和不使用 var 声明变量的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16931126/

相关文章:

go - 主golang中的自定义包

mongodb - 确保 MongoDB 以动态时间间隔使数据过期并且调用是幂等的

go - 如何在 if-else 中初始化错误类型

google-app-engine - 在 Go 中合并独立的 webapp 和 GAE

java - ArrayIndexOutOfBoundsException/将 arraylist 从 alertdialog 传递到 Activity

go - 计算Golang中的最近点

c++ - 我将如何创建一个可以具有非零下限的 Array 类(在 C++ 中)?

java - 奇怪的 ArrayIndexOutOfBoundsException

Java try catch 不处理 IndexOutOfBoundsException

Java 数组索引越界