如何将函数调用追加到golang结构?

时间:2017-04-24 19:57:17

标签: go data-structures

我有以下go代码,我想让接口工作:

https://play.golang.org/p/A29etweYN_

提供以下输出:

Gate: Evaluation ID U0 NOR true 0 0
Gate: Evaluation ID U1 NOR false 0 1
Gate: Evaluation ID U2 NOR false 1 0
Gate: Evaluation ID U3 NOR false 1 1

我发现很难理解为什么注释掉的行

//OutputY: gateNor(InputA,InputB) 

不起作用 - gateNor是一个我想调用并附加到Gate结构

的函数

实现这一目标的更优雅方式是什么?

type Gate struct {
   Id      string
   Funct   string
   InputA  string
   InputB  string
   OutputY string
}

func (g *Gate) Notify() error {
    fmt.Printf("Gate: Evaluation ID %s %s %s %s %s\n",
        g.Id,
        g.Funct,
        g.OutputY,
        g.InputA,
        g.InputB,
    )
    return nil
}

gate0 := &Gate{
    Id:      "U0",
    Funct:   "NOR",
    InputA:  "0",
    InputB:  "0",
    OutputY: gateNor("0", "0"),
    //OutputY: gateNor(InputA,InputB),
}

对于输入A = 0和InputB = 0,gateNor返回字符串true, 对于gate0(ID U0)结构,输出正在工作:

Gate: Evaluation ID U0 NOR true 0 0

3 个答案:

答案 0 :(得分:3)

例如,

gate0 := &Gate{
    Id:     "U0",
    Funct:  "NOR",
    InputA: "0",
    InputB: "0",
}
gate0.OutputY = gateNor(gate0.InputA, gate0.InputB)

或者,更优雅,

func NewNORGate(id, a, b string) *Gate {
    gate := &Gate{
        Id:     id,
        Funct:  "NOR",
        InputA: a,
        InputB: b,
    }
    gate.OutputY = gateNor(gate.InputA, gate.InputB)
    return gate
}

func main() {
    gate0 := NewNORGate("U0", "0", "0")
    gate1 := NewNORGate("U1", "0", "1")
    gate2 := NewNORGate("U2", "1", "0")
    gate3 := NewNORGate("U3", "1", "1")

    GetEvaluation(gate0)
    GetEvaluation(gate1)
    GetEvaluation(gate2)
    GetEvaluation(gate3)
}

https://play.golang.org/p/WC-jlV-jqd

或者,最优雅的是,

func NewNORGate(id, a, b string) *Gate {
    gate := &Gate{
        Id:     id,
        Funct:  "NOR",
        InputA: a,
        InputB: b,
    }
    gate.OutputY = gateNor(gate.InputA, gate.InputB)
    return gate
}

func main() {
    GetEvaluation(NewNORGate("U0", "0", "0"))
    GetEvaluation(NewNORGate("U1", "0", "1"))
    GetEvaluation(NewNORGate("U2", "1", "0"))
    GetEvaluation(NewNORGate("U3", "1", "1"))
}

https://play.golang.org/p/TOPuwSJ-xe

答案 1 :(得分:1)

你不能在object-initializer中引用Gate的成员;你可以这样做:

inputA, inputB := "1", "1"
gate3 := &Gate{
    Id:      "U3",
    Funct:   "NOR",
    InputA:  inputA,
    InputB:  inputB,
    OutputY: gateNor(inputA,inputB),
}

答案 2 :(得分:1)

也许不是太优雅,但我宁愿定义方法

  

将函数调用附加到golang结构

type Gate struct {
   Id      string
   Funct   string
   InputA  string
   InputB  string
}
func (g Gate) OutputY()string{
   return gateNor(g.InputA, g.InputB)
}

并且

g.OutputY()

懒洋洋地按需求。 g.OutputY() g.OutputY并不比g.OutputY()更详细,在计算困难的情况下,懒惰就很重要。同时根据要求,您可以获得g.Output的一致值。在更改说g.InputA="1"之后,您如何假设另一种方式维持{{1}}?