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 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应