未导出的结构最佳实践?(戈林特抱怨)

我有以下包裹:


package mypkg


type (

    // mystruct ...

    mystruct struct {

        S string

    }

)


// New ..

func New() *mystruct {

    return &mystruct{S: "test"}

}

我这样使用它:


package main


import (

    "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 调用的情况下实例化?


郎朗坤
浏览 178回答 1
1回答

三国纷争

你x := mypkg.New()在 main.main() 甚至不能有任何类型。它甚至不应该编译。它无法使用。在我看来更有意义的是package mypkgtype (    // 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.HaveSx = mypkg.New()fmt.Println(x.GetS())
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go