Go 嵌套方法能否访问父级';s的价值观?
我试图创建状态的字符串视图,因此调用时:Go 嵌套方法能否访问父级';s的价值观?,go,Go,我试图创建状态的字符串视图,因此调用时: fmt.Printf("%s", panel.State) 它将打印出如下内容: Hi ⚪️⚪️⚪️⚪️⚪️⚪️⚪️⚪️⚪️⚪️ ⚪️⚫️⚪️⚫️⚪️⚪️⚫️⚪️⚪️⚪️ ⚪️⚫️⚪️⚫️⚪️⚪️⚪️⚪️⚪️⚪️ ⚪️⚫️⚫️⚫️⚪️⚪️⚫️⚪️⚪️⚪️ ⚪️⚫️⚪️⚫️⚪️⚪️⚫️⚪️⚪️⚪️ ⚪️⚫️⚪️⚫️⚪️⚪️⚫️⚪️⚪️⚪️ ⚪️⚪️⚪️⚪️⚪️⚪️⚪️⚪️⚪️⚪️ type Panel struct { Width int H
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
}
是否可以在嵌套字段上添加方法,然后访问其父结构,例如:
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
}
类型面板结构{
宽度整数
高度整数
消息字符串
州[]布尔
}
func(state Panel.state)String()字符串{
行:=state.parent.Message+“\n”
对于x:=0;x
不,不可能。但是,您可以定义一个新类型(类型状态[][]bool
)并在此基础上定义字符串方法。如果您定义了一个新类型,那么我如何才能访问父级的Width
和Height
字段?如果没有明确的引用,则无法访问。如果这是您需要的,请在面板类型上定义一个新方法。也许您可以更新您的问题。您的示例显示了<代码>宽度或高度字段。建议的类型状态[][]bool
解决方案符合您的示例updated@Patrick的条件,谢谢!