简体   繁体   English

在Go中间接更改结构中的值

[英]Indirectly change a value in a struct in Go

I have the following code, feel free to offer pointers if you wish: 我有以下代码,如果您愿意,可以随时提供指针:

package main

import (
  "fmt"
)

type Grid struct {
  rows int
  cols int
  tiles []Tile
}

type Tile struct {
  x int
  y int
  contents int
}

func (g Grid) AddTile(t Tile) {
  g.tiles = append(g.tiles, t)
}

func (g *Grid) Row(num int) []Tile {
  numTiles := len(g.tiles)
  row := []Tile{}
  for i := 0; i < numTiles; i++ {
    tile := g.tiles[i]
    if (tile.y == num) {
      row = append(row, tile)
    }
  }
  return row
}

/*
  HERE IS WHERE I NEED HELP
*/
func (g *Grid) SetRow(num, val int) {
  row := g.Row(num)
  rowLength := len(row)
  for i := 0; i < rowLength; i++ {
    tile := &row[i]
    tile.contents = val
  }
}

func (g Grid) Col(num int) []Tile {
  numTiles := len(g.tiles)
  col := []Tile{}
  for i := 0; i < numTiles; i++ {
    tile := g.tiles[i]
    if (tile.x == num) {
      col = append(col, tile)
    }
  }
  return col
}

func MakeTile(x, y int) Tile {
  tile := Tile{x: x, y: y}
  return tile
}

func MakeGrid(rows, cols int) Grid {
  g := Grid{ rows: rows, cols: cols}
  for r := 1; r <= rows; r++ {
    for c := 1; c <= cols; c++ {
      g.tiles = append(g.tiles, MakeTile(r, c))
    }
  }
  return g
}

func main() {
  g := MakeGrid(256, 256)
  g.SetRow(100, 5)
  fmt.Println(g.Row(100))
}

I am doing this, more than anything, as a simple project to help me learn Go. 作为一个帮助我学习Go的简单项目,我要做的比什么都重要。 The problem that is have run in to is here 遇到的问题在这里

/*
  HERE IS WHERE I NEED HELP
*/
func (g *Grid) SetRow(num, val int) {
  row := g.Row(num)
  rowLength := len(row)
  for i := 0; i < rowLength; i++ {
    tile := &row[i]
    tile.contents = val
  }
}

Somewhere it seems like I need to be making a pointer to the actual Tiles that I'm trying to modify. 似乎在某个地方,我需要指向要尝试修改的实际Tiles的指针。 As it is the SetRow function doesn't actually modify anything. 因为它是SetRow函数,实际上并没有修改任何内容。 What am I doing wrong? 我究竟做错了什么? Keep in mind I just started learning Go 2 days ago, so this is a learning experience :) 请记住,我两天前才开始学习Go,所以这是一种学习体验:)

One way to accomplish your goal is to use pointers to tiles throughout the code. 一种实现目标的方法是在整个代码中使用指向图块的指针。 Change the Grid tiles field to: 将网格图块字段更改为:

tiles []*Tile

and several related changes through the code. 以及代码中的一些相关更改。

Also, change all the methods to use pointer receivers. 此外,更改所有方法以使用指针接收器。 The AddTile method as written in the question discards the modification to the grid on return. 问题中所写的AddTile方法会在返回时放弃对网格的修改。

playground example 游乐场的例子

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM