dongxi5494 2016-03-30 16:24
浏览 41
已采纳

Go语言:XXX类型不是表达式

I have written a function:

func Pic(dx, dy int) [][]uint8 {
    type matrix [][]uint8 

    for i := 0; i < dx; i++ { // fills up the matrix with z's in their right places.
        for j := 0; j < dy; j++ {
            matrix[i][j] = Z(i,j)
        }
    }

    return matrix
}

that is supposed to fill up a matrix with z values for each x and y value and return it. As I want to have different dimensions for the matrix depending of parameters to the Pic function, I create a slice i line 2. Then in my for loops i fill the matrix up.

I get an error upon running this code: type matrix is not an expression for the matrix[i][j] = Z(i,j) line. What am I doing wrong? Should matrix[i][j] evaluate to an expression? Why should it, when I want to put something there (it's empty/non-existent now!) ?

  • 写回答

2条回答 默认 最新

  • dongqiang8474 2016-03-30 17:09
    关注

    While you can use var matrix [][]uint8, I'd recommend using the built-in make function since you know the desired lengths—dx for the outer slice and dy for the inner slice. The Two-dimensional slices section of Effective Go gives an example of using make to allocate a two-dimensional slice. Below is an example for your Pic function.

    func Pic(dx, dy int) [][]uint8 {
        matrix := make([][]uint8, dx)
    
        for i := 0; i < dx; i++ {
            matrix[i] = make([]uint8, dy)
            for j := 0; j < dy; j++ {
                matrix[i][j] = Z(i, j)
            }
        }
        return matrix
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序