什么时候应该是一个包含另一个类型的结构,什么时候应该只是“扩展”(?)那种类型? [英] When should a type be a struct containing another type and when should it just "extend"(?) that type?

查看:138
本文介绍了什么时候应该是一个包含另一个类型的结构,什么时候应该只是“扩展”(?)那种类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前通过执行 rosalind问题(基本上是一组与生物信息相关的代码katas)来学习Go。



我现在用一个类型表示DNA链:

  type DNAStrand struct {
dna byte []
}

我的初始原因是封装字节片,所以我知道它只包含代表核苷酸的字节:'A','C','G','T'。我意识到这显然没有被保留,因为我可以简单地做:
$ b

  DNAStrand {[] byte(foo bar)} 

不再保证我的dna链只包含一个字节数组,只有这四个元素字节。

由于我的结构只包含一个字节数组,所以它可以做得更好/更具意义:



<$ p $或者是更好地让这种类型的数据类型更好,例如: type DNAStrand [] byte

包含DNA链?对于何时使用这两种方法,有什么经验法则?

解决方案

具有零字段的结构非常方便。许多领域的结构更方便。只有一个领域的结构有点特殊,我不能想到使用它们的合理好情况 - 即使它们经常在野外看到。不管怎样,如果你确实需要对 DNAStrand slice内容 - 那么可以使用单个字段struct并为这个/这样的命名类型定义一个参数检查setter方法。



在这种情况下,如果稍后从其他软件包中使用该定义,则无法使用软件包不安全进行模仿,以避免检查并得到相当于您的 DNAStrand {[] byte(foo bar)} 例子的结果。


I'm currently learning Go by doing the rosalind problems (basically a bunch of bioinformatics related code katas).

I'm currently representing a DNA strand with a type:

type DNAStrand struct {
    dna byte[]
}

My initial reason was to encapsulate the byte slice so I would know it only contained bytes representing the nucleotides: 'A', 'C', 'G', 'T'. I realized that this was obviously not guarateed since I could simply do:

DNAStrand{[]byte("foo bar")}

And there is no longer any guarantee that my dna strand contains a byte array with only elements from those four bytes.

Since my struct only contains a byte array is it better/more ideomatic to do:

type DNAStrand []byte

Or is it better to let the type contain the dna strand? Are there any rules of thumb for when to use either of the two approaches?

解决方案

Struct with zero fields are handy. Structs with many fields are handy even more. Structs with exactly one field are a bit special and I can't think of a reasonably "good" case where to use them - even though they are seen regularly "in the wild". I, for one, don't use them.

Anyway, if you really really need tighter/bulletproof safety about the DNAStrand slice content - then it is possible to to use the single field struct and define an argument checking setter method for this/such named type.

In that case, if the definition is later used from some other package, there's no way, modulo using package unsafe, to circumvent the checks and get a result equivalent to your DNAStrand{[]byte("foo bar")} example.

这篇关于什么时候应该是一个包含另一个类型的结构,什么时候应该只是“扩展”(?)那种类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆