我正处于了解Go中接口的早期阶段。我正在写一些逻辑模拟,并且有类似下面的代码(我在这里大大简化):
请参阅我的问题的评论:
type LogicNode struct {
Input *bool
Output *bool
Operator string
Next Node
}
func (n *LogicNode) Run() {
// do some stuff here
n.Next.Run()
}
type Node interface {
Run()
}
func main() {
nodes := make([]Node, 1000)
for i := 0; i < 1000; i++ {
n := LogicNode{
//assign values etc.
}
nodes[i] = &n
}
for i, node := range nodes {
// I need to access LogicNode's Output pointer here, as a *bool.
// so I can set the same address to other Node's Input thereby "connecting" them.
// but I could only get something like this:
x := reflect.ValueOf(node).Elem().FieldByName("Output")
// which is <*bool Value>
// I couldn't find a way to set a new *bool to the underlying (LogicNode) Struct's Input or Output..
}
}
我使用接口的原因是因为有其他节点类型FloatNode MathNode等具有不同的字段,但它们实现了自己的run方法。
我已经成功使用了Value的SetString或SetBool方法,但是无法在那里设置指针...在此先感谢。
答案 0 :(得分:9)
您可以使用Set通用版本来更新字段值:
package main
import (
"fmt"
"reflect"
)
type LogicNode struct {
Input *bool
Output *bool
Operator string
Next Node
}
func (n *LogicNode) Run() {
// do some stuff here
// n.Next.Run()
fmt.Printf("LogicNode.Input = %v (%v)\n", *n.Input, n.Input)
}
type Node interface {
Run()
}
func main() {
input := false
input2 := true
fmt.Printf("Input1 = %v (%v)\n", input, &input)
fmt.Printf("Input2 = %v (%v)\n", input2, &input2)
var node Node = &LogicNode{Input: &input} // Remember, interfaces are pointers
node.Run()
x := reflect.ValueOf(node).Elem().FieldByName("Input")
x.Set(reflect.ValueOf(&input2))
node.Run()
}
输出:
Input1 = false (0x10500168)
Input2 = true (0x10500170)
LogicNode.Input = false (0x10500168)
LogicNode.Input = true (0x10500170)
游乐场here。