Pointers Golang-通过接口获取指向结构字段的指针

Pointers Golang-通过接口获取指向结构字段的指针,pointers,reflection,go,Pointers,Reflection,Go,我在理解Go中的接口方面还处于非常早期的阶段。我正在编写一些逻辑模拟,代码如下(我在这里进行了大量简化): 关于我的问题,请参见评论: type LogicNode struct { Input *bool Output *bool Operator string Next Node } func (n *LogicNode) Run() { // do some stuff here n.Next.Run() } type N

我在理解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..
    }
}
类型LogicNode结构{
输入*bool
输出*bool
运算符字符串
下一节点
}
func(n*LogicNode)运行(){
//在这里做些事情
n、 Next.Run()
}
类型节点接口{
运行()
}
func main(){
节点:=make([]节点,1000)
对于i:=0;i<1000;i++{
n:=逻辑节点{
//赋值等。
}
节点[i]=&n
}
对于i,节点:=范围节点{
//我需要在这里访问LogicNode的输出指针,作为*bool。
//因此,我可以为其他节点的输入设置相同的地址,从而“连接”它们。
//但我只能得到这样的东西:
x:=reflect.ValueOf(node.Elem().FieldByName(“输出”)
//那是
//我找不到将新*bool设置为基础(LogicNode)结构的输入或输出的方法。。
}
}
我之所以使用接口,是因为还有其他节点类型floatNodeMathNode等,它们有不同的字段,但它们实现自己的运行方法

我已经成功地使用了Value的SetString或SetBool方法,但无法在那里设置指针。。。提前谢谢

您可以使用通用版本更新字段值:

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)

操场。

纯粹的幸福:)谢谢你!为什么不直接将节点转换为LogicNode和access字段呢?好建议,这是另一种解决方案。如果将有相当多的类型,而不是那么多的领域,这是不明显的,这是更好的。