dougu4027 2016-02-05 04:47
浏览 5
已采纳

在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. 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. As it is the SetRow function doesn't actually modify anything. What am I doing wrong? Keep in mind I just started learning Go 2 days ago, so this is a learning experience :)

  • 写回答

1条回答 默认 最新

  • dongshuxi3105 2016-02-05 05:45
    关注

    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.

    playground example

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线