gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 00:54:41 27 4
gpt4 key购买 nike

我在使用 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com