【问题标题】:struct embeding, function inputs, polymorphism结构嵌入、函数输入、多态性
【发布时间】:2019-07-17 08:54:16
【问题描述】:

我有一个父结构:

type BigPoly struct{
    Value []*ring.Poly
}

还有两个子结构:

type Plaintext BigPoly
type Ciphertext BigPoly

我想要同时接受明文和密文的函数。我的解决方案是使用以下形式的功能:

func Add(a *Ciphertext, b interface{}) (*Ciphertext)

并使用 switch-case 来决定要做什么,但我觉得它很麻烦,如果输入的数量增加,它可能会导致非常复杂的情况。

但是,由于明文和密文具有完全相同的结构和内部变量,只是名称不同,是否可以以更简洁的方式创建一个同时接受明文和密文的函数? IE。它不关心是明文类型还是密文类型,只要是 BigPoly 类型即可。

【问题讨论】:

  • Go 中没有“子”或“父”结构。您拥有的是不同的类型,没有父/子关系。
  • 解决问题的正确方法是使用接口(不是空接口)。也许interface Poly { Value() []*ring.Poly }。然后让你的函数接受那个接口。

标签: function go input struct types


【解决方案1】:

使用非空接口:

type Poly interface {
    Value() []*ring.Poly
}

然后将你的结构定义为:

type BigPoly struct{
    value []*ring.Poly
}

func (p *BigPoly) Value() []*ring.Poly {
    return p.value
}

你的消费者是:

func Add(a, b Poly) Poly {
    aValue := a.Value()
    bValue := b.Value()
    // ... do something with aValue and bValue
}

【讨论】:

  • 谢谢。但是密文和明文类型在哪里适合呢?我仍然希望能够区分它们。
  • 您仍然可以使用它们。只要确保它们满足界面即可。
  • 是的,我的错,它运作良好,非常感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多