[英]Golang struct construction generality
我有一個其他兩個對象實現的結構。 在這種情況下,鍵入A和B repo。 有一些初始化代碼,在這里表示為省略號。 初始化代碼在兩個構造函數之間完全重復,並且不是什么大問題,而我只有兩個dbRepo
,但是當我創建更多時,我會更擔心不良實踐。 有沒有辦法用界面來概括這個?
type dbRepo struct {
foo string
bar string
}
type typeARepo dbRepo
type typeBRepo dbRepo
func newTypeARepo(foo, bar string) {
...
}
func newTypeBRepo(foo, bar string) {
...
}
我個人在Go中觀察到的這種做法(也是有效的Go或者Go教程入門中推薦的NewdbRepo
)就是定義一個NewdbRepo
函數並將其用於所有瞬時。 它的實現看起來像;
func NewdbRepo(f, b string) *dbRepo {
return &dbRepo{ foo:f, bar:b}
}
您無法像在大多數C語言中那樣實際定義構造函數,因此您只需提供一個包作用域的方法來為您構建。 此外,如果您沒有使用復合文字(我在NewdbRepo實現中使用的啟動樣式),那么您可能會發現它足夠簡潔以滿足您的需求。
您可以使用初始化代碼編寫一個函數:
func newDbRepo(foo, bar string) dbRepo {
// ...
}
然后你可以使用它與類型轉換:
a := typeARepo(newDbRepo("foo", "bar"))
b := typeBRepo(newDbRepo("foo", "bar"))
在執行初始化的類型上定義未導出的func,然后您可以創建幾個調用它的構造函數,例如:
func (db *dbRepo) init(){
if len(db.foo) > 0 {
//do foo init
}
if len(db.bar) > 0 {
// do bar init
}
// do generic init
}
func NewRepo(foo, bar string) *dbRepo {
repo := &dbRepo{foo: foo, bar: bar}
repo.init()
return repo
}
func NewFooRepo(foo string) *dbRepo {
repo := &dbRepo{foo: foo}
repo.init()
return repo
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.