猿问

更新切片中的一个位置会导致多次更新

我学习去玩切片,但我有一个问题


我有一个带有“.”的默认矩阵,但是当我尝试将位置0,0更改为“#”符号时,所有n,0位置都有一个“#”,换句话说,我从这个开始:


[. . . . .]

[. . . . .]

[. . . . .]

[. . . . .]

[. . . . .]

使用此功能修改 0,0 位置:


func drawSym(table *[][]string) {

    (*table)[0][0] = "#" 

}

我得到


[# . . . .]

[# . . . .]

[# . . . .]

[# . . . .]

[# . . . .]

当我想要这样的矩阵时


[# . . . .]

[. . . . .]

[. . . . .]

[. . . . .]

[. . . . .]

该计划的完整代码位于游乐场 https://play.golang.org/p/xvkRhmNvdIP


qq_遁去的一_1
浏览 129回答 3
3回答

UYOU

如果矩阵大小未更改,则无需传入指向切片(或切片)的指针。因此,您可以简化表的创建/初始化,如下所示:func createTable(size int) (table [][]string) {&nbsp; &nbsp; table = make([][]string, size)&nbsp; &nbsp; for i := 0; i < size; i++ {&nbsp; &nbsp; &nbsp; &nbsp; table[i] = make([]string, size) // create a new row per iteration&nbsp; &nbsp; &nbsp; &nbsp; for j := 0; j < size; j++ {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; table[i][j] = "."&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return}table := createTable(5)和 函数也得到了简化 - 因为它们也不需要切片指针:drawprinthttps://play.golang.org/p/KmwynzUj0I-

暮色呼如

如果矩阵的大小是固定的,则可以使用数组而不是切片 ()。为了防止代码重复并简化维护,您可以为该矩阵 () 创建所需长度的类型,并在代码 () 中使用该类型。[5][5]stringtype myMatrix [5][5]stringfunc printTable(table myMatrix)如package mainimport (&nbsp; &nbsp; "fmt")type myMatrix [5][5]stringfunc main() {&nbsp; &nbsp; var table myMatrix&nbsp; &nbsp; for i := 0; i < len(table); i++ {&nbsp; &nbsp; &nbsp; &nbsp; for j := 0; j < len(table); j++ {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; table[i][j] = "."&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; table[0][0] = "#"&nbsp; &nbsp; printTable(table)}func printTable(table myMatrix) {&nbsp; &nbsp; for i := 0; i < len(table); i++ {&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println(table[i])&nbsp; &nbsp; }}https://play.golang.org/p/Ok0DBGSfJlA

哔哔one

按如下方式修改代码,以便不会在所有行中获取相同的值,为每次迭代创建一个新行,而不是使用相同的行。package mainimport (&nbsp; &nbsp; "fmt")func main() {&nbsp; &nbsp; table := make([][]string, 5)&nbsp; &nbsp; initTable(table)&nbsp; &nbsp; printTable(table)&nbsp; &nbsp; drawSym(table)&nbsp; &nbsp; printTable(table)}func drawSym(table [][]string) {&nbsp; &nbsp; (table)[0][0] = "#"&nbsp; &nbsp; (table)[1][1] = "%"}func initTable(table [][]string) {&nbsp; &nbsp; for i := 0; i < len(table); i++ {&nbsp; &nbsp; &nbsp; &nbsp; table[i] = make([]string, len(table))&nbsp; &nbsp; &nbsp; &nbsp; for j := 0; j < len(table); j++ {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; table[i][j] = "."&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}func printTable(table [][]string) {&nbsp; &nbsp; for i := 0; i < len(table); i++ {&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println((table)[i])&nbsp; &nbsp; }}输出:[. . . . .][. . . . .][. . . . .][. . . . .][. . . . .][# . . . .][. % . . .][. . . . .][. . . . .][. . . . .]
随时随地看视频慕课网APP

相关分类

Go
我要回答