簡體   English   中英

Golang - 通過接口獲取指向結構字段的指針

[英]Golang - Get a pointer to a field of a struct through an interface

我正處於了解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方法,但無法在那里設置指針...提前感謝。

您可以使用Set generic version更新字段值:

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)

這里的游樂場。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM