如何将函数调用追加到golang结构?
我有以下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 %sn",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, Gate: Evaluation ID U0 NOR true 0 0 解决方法
例如,
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,InputA: a,InputB: b,} gate.OutputY = gateNor(gate.InputA,gate.InputB) return gate } func main() { gate0 := NewNORGate("U0","0","0") gate1 := NewNORGate("U1","1") gate2 := NewNORGate("U2","1","0") gate3 := NewNORGate("U3","1") GetEvaluation(gate0) GetEvaluation(gate1) GetEvaluation(gate2) GetEvaluation(gate3) } https://play.golang.org/p/WC-jlV-jqd 或者,最优雅的,gate.InputB) return gate } func main() { GetEvaluation(NewNORGate("U0","0")) GetEvaluation(NewNORGate("U1","1")) GetEvaluation(NewNORGate("U2","0")) GetEvaluation(NewNORGate("U3","1")) } https://play.golang.org/p/TOPuwSJ-xe (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |