我有以下包裹:package mypkgtype ( // mystruct ... mystruct struct { S string })// New ..func New() *mystruct { return &mystruct{S: "test"}}我這樣使用它:package mainimport ( "fmt" "test/mypkg")func main() { x := mypkg.New() fmt.Println(x.S) // this fails intended y := mypkg.mystruct{S: "andre"} fmt.Println(y.S)}為什么 golint 抱怨我未導出的結構?我的意圖是防止在構造函數調用之外調用結構創建。是否有另一種方法可以防止在沒有 New 調用的情況下實例化?
1 回答

三國紛爭
TA貢獻1804條經驗 獲得超7個贊
你x := mypkg.New()在 main.main() 甚至不能有任何類型。它甚至不應該編譯。它無法使用。在我看來更有意義的是
package mypkg
type (
// mystruct ...
mystruct struct {
S string
}
)
type HaveS interface{ //which you can use but can't instantiate
GetS() string
}
func (strct *mystruct ) GetS() string {return strct.S}
// New ..
func New() HaveS {
return &mystruct{S: "test"}
}
然后在主要
var x mypkg.HaveS
x = mypkg.New()
fmt.Println(x.GetS())
- 1 回答
- 0 關注
- 148 瀏覽
添加回答
舉報
0/150
提交
取消