# 具有类型约束的 Go 泛型：不能在赋值中使用 false（无类型布尔常量）作为 T 值

2022-11-23 19:50:21

func createGrid[T int | bool](size int, forFlooded bool) [][]T {

var tempGrid [][]T

for i := 0; i <= size+1; i++ {

for j := 0; j <= size+1; j++ {

if forFlooded {

tempGrid[i][j] = false

} else {

tempGrid[i][j] = -1

}

}

}

return tempGrid

}

cannot use false (untyped bool constant) as T value in assignment

cannot use -1 (untyped int constant) as T value in assignment

var grid [][]int;

grid = createGrid(n, false);

var flooded [][]bool;

flooded = createGrid(n, true);

## 1 回答

TA贡献1514条经验 获得超6个赞

func createGridInt(size int, forFlooded bool) [][]int {

var tempGrid [][]int

for i := 0; i <= size+1; i++ {

for j := 0; j <= size+1; j++ {

if forFlooded {

tempGrid[i][j] = false

} else {

tempGrid[i][j] = -1

}

}

}

return tempGrid

}

func createGridBool(size int, forFlooded bool) [][]bool {

var tempGrid [][]bool

for i := 0; i <= size+1; i++ {

for j := 0; j <= size+1; j++ {

if forFlooded {

tempGrid[i][j] = false

} else {

tempGrid[i][j] = -1

}

}

}

return tempGrid

}

func createGrid[T int | bool](size int, fillWith T) [][]T {

var tempGrid [][]T

for i := 0; i <= size+1; i++ {

for j := 0; j <= size+1; j++ {

tempGrid[i][j] = fillWith

}

}

return tempGrid

}

createGrid(n, false)

createGrid(n, -1)

• 1 回答
• 0 关注
• 8 浏览

0/150