英文:
Go language: Type XXX is not an expression
问题
我写了一个函数:
func Pic(dx, dy int) [][]uint8 {
type matrix [][]uint8
for i := 0; i < dx; i++ { // 用 z 的正确位置填充矩阵。
for j := 0; j < dy; j++ {
matrix[i][j] = Z(i,j)
}
}
return matrix
}
这个函数的目的是为每个 x 和 y 值填充一个包含 z 值的矩阵,并返回它。由于我想根据 Pic 函数的参数设置矩阵的不同维度,所以我在第 2 行创建了一个切片。然后在我的循环中填充矩阵。
运行这段代码时,我收到一个错误:type matrix is not an expression
,出现在 matrix[i][j] = Z(i,j)
这一行。我做错了什么?matrix[i][j]
应该评估为一个表达式吗?为什么应该这样,当我想要在那里放置一些东西时(它现在是空的/不存在!)?
英文:
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!) ?
答案1
得分: 6
你将matrix
声明为一种类型,但在使用时将其作为变量。
尝试使用以下代码:
var matrix [][]uint8
英文:
You're declaring matrix
as a type, but using it as a variable.
try:
var matrix [][]uint8
答案2
得分: 4
你可以使用var matrix [][]uint8
,但我建议使用内置的make
函数,因为你知道外部切片的长度dx
和内部切片的长度dy
。Effective Go的Two-dimensional slices部分提供了使用make
函数分配二维切片的示例。下面是一个适用于你的Pic
函数的示例代码:
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
}
英文:
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
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论