3 回答

TA貢獻(xiàn)2019條經(jīng)驗(yàn) 獲得超9個(gè)贊
具有零字段的結(jié)構(gòu)很方便。具有許多領(lǐng)域的結(jié)構(gòu)更加方便。僅具有一個(gè)字段的結(jié)構(gòu)有點(diǎn)特殊,即使在“野外”經(jīng)常看到它們,我也想不出在哪里使用它們的合理“好”案例。我,一個(gè),不要使用它們。
無論如何,如果您真的真的需要更嚴(yán)格/更安全的DNAStrand
切片內(nèi)容安全性,那么可以使用單個(gè)字段結(jié)構(gòu)并為此/此類命名類型定義參數(shù)檢查設(shè)置方法。
在那種情況下,如果以后在其他軟件包中使用該定義,則無法使用軟件包unsafe進(jìn)行模運(yùn)算來規(guī)避檢查并獲得與您的DNAStrand{[]byte("foo bar")}
示例相同的結(jié)果。

TA貢獻(xiàn)1883條經(jīng)驗(yàn) 獲得超3個(gè)贊
以您的特定示例為例,我可能會(huì)執(zhí)行以下操作:
type neucleotide char // unexported type users can't construct their own.
type DNAStrand []neucleotide // because users can't construct their own
// nucleotides they also can't construct their
// own DNAStrands.
const (
// These are exported values so they can use these nucleotides to construct a
// DNAStrand with.
A nucleotide = 'A'
C nucleotide = 'C'
G nudleotide = 'G'
T nucleotide = 'T'
)
// This function allows them to actually construct a DNAstrand with a list of
// nucleotides from the constants above.
func New(nts ...nucleotide) DNAStrand {
return nts
}
由于不輸出核苷酸類型,因此用戶無法構(gòu)建自己的核苷酸。您在導(dǎo)出的const中提供了它們的唯一允許實(shí)例,因此沒有用戶可以提供自己的新核苷酸。
- 3 回答
- 0 關(guān)注
- 225 瀏覽
添加回答
舉報(bào)