dongzhe3573 2013-06-05 03:36
浏览 96
已采纳

go中使用var与不使用var声明变量之间的区别

I was having some trouble with step 35 in the tour of Go exercise.

Here's what my code looks like:

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
}

When looking for a solution, I found PeterSO's code which works perfectly

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
}

The only difference I can see, is that I'm defining the pic variable using the var keyword whereas his code is using the := assignment. Now, why does my code not work?

  • 写回答

2条回答 默认 最新

  • douxuanpa8298 2013-06-05 03:42
    关注

    If you use the :=, the type of the variable is implied from the expression on the right of the sign. If you use =, no assumption is made and you need to specify the type yourself.

    In this case, you should write it like this:

    var pic [][]uint8 = make([][]uint8, dy)
    

    but this is indeed better because shorter and as clear:

    pic := make([][]uint8, dy)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥100 求三轴之间相互配合画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站