dtc66318 2018-11-28 22:00
浏览 28
已采纳

尝试了解如何从int参数建立数组

All:

When I try to follow golang's Tour of Go:

Exercise: Slices

My code is like this:

package main

import "golang.org/x/tour/pic"

func Pic(dx, dy int) [][]uint8 {
    const x = dx
    const y = dy
    pic := [y][x]uint8{};

    for r:=range pic {
        row := pic[r]
        for c := range row {
            row[c] = uint8(c*r) 
        }
    }

    return pic[:]
}

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

And I got error like:

prog.go:6:8: const initializer dx is not a constant
prog.go:7:8: const initializer dy is not a constant

I am pretty new to Go, I wonder what this error means, and if I want to build an array first(other than using make() to build slice), how can I pass the length of array?

  • 写回答

2条回答 默认 最新

  • ds3422222222 2018-11-28 22:10
    关注

    The Error

    The error comes from trying to define a constant from a variable. In Go, constants must be defined as literals or expressions built from other constants. Your x and y are defined differently depending on the input of the Pic function. In general, constants are defined at compile time.

    For example the following are fine in Go:

    const w = 100
    const x = 200
    const y = w + x
    const z = x + y + 300
    

    But the following is not:

    var x = 100
    const y = x + 10
    

    and this second example is essentially what is happening in your code since dx and dy vary depending on the input to the Pic function.

    If you're coming from JavaScript, which also has the const keyword, this might seem like strange behavior. In JavaScript a constant is basically just a variable that can't be changed after it is declared. In Go, a constant is more constant than in JS.

    Check out this post for more on constants in Go: https://blog.golang.org/constants

    Creating the Array

    Array sizes have similar constraints to constant values in Go. In this example, if you try to set the Array's size equal to dx or dy, you will get the error:

    non-constant array bound dx

    Thus you will have to use a Slice in this example. The simplest way would be to define your Slice with length dy like:

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

报告相同问题?

悬赏问题

  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 MATLAB中streamslice问题
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序