首页 > 解决方案 > 嵌套方法可以访问父级的值吗?

问题描述

我正在尝试创建状态的字符串视图,因此在调用时:

fmt.Printf("%s", panel.State)

它将打印出如下内容:

Hi
⚪️⚪️⚪️⚪️⚪️⚪️⚪️⚪️⚪️⚪️
⚪️⚫️⚪️⚫️⚪️⚪️⚫️⚪️⚪️⚪️
⚪️⚫️⚪️⚫️⚪️⚪️⚪️⚪️⚪️⚪️
⚪️⚫️⚫️⚫️⚪️⚪️⚫️⚪️⚪️⚪️
⚪️⚫️⚪️⚫️⚪️⚪️⚫️⚪️⚪️⚪️
⚪️⚫️⚪️⚫️⚪️⚪️⚫️⚪️⚪️⚪️
⚪️⚪️⚪️⚪️⚪️⚪️⚪️⚪️⚪️⚪️

是否可以在嵌套字段上添加方法,然后可以访问它的父结构,例如:

type Panel struct {
  Width  int
  Height int
  Message string

  State [][]bool
}

func (state Panel.State) String() string {
  line := state.parent.Message + "\n"
  for x := 0; x < state.parent.Width; x++ {
    for y := 0; y < state.parent.Height; y++ {
      cell = state[x][y]
      if cell {
        line += "⚫️"
      } else {
        line += "⚪️"
      }
    }
    line += "\n"
  }

  return line
}

标签: go

解决方案


推荐阅读