doufan8805 2016-06-21 18:50 采纳率: 0%
浏览 258
已采纳

golang私有结构的公共方法-有任何用例

I am new to go. I noticed in some libraries there are public methods to a private struct. See for example https://github.com/btcsuite/btcd/blob/master/txscript/stack.go

Does this have a real use case? I cannot picture how I will be able to use public methods, if I cannot access the structure they belong too.

As the following question - is there any way to overcome the private declaration of a struct? For example, I would like to use the structure stack from the pointed file in my package.

  • 写回答

2条回答 默认 最新

  • dtcu5885 2016-06-21 19:15
    关注

    So, the major use case for this is that you can return an unexported type from a package function. Any exported methods can then be used on this type, even though other packages can't actually create the type in the first place (except for receiving it as a return value from your package).

    package foobar
    
    type foo struct {}
    func (f foo) Bar() {}
    func Newfoo() foo {
        return foo{}
    }
    ----
    package main
    func main() {
        f := foobar.Newfoo()
        f.Bar()
    
        foobar.NewFoo().Bar()
    }
    

    The other major use case is in package-level interfaces. I tend to use a fairly standard pattern wherein a package defines an exported interface, like this:

    type Doer interface {
        Do()
    }
    

    And then defines some private type(s) that fulfills that interface:

    type stringDoer struct {}
    
    func (s *stringDoer) Do() {}
    
    func NewStringDoer() Doer {
        return &stringDoer{}
    }
    

    That way external packages can use my types as interfaces without having to mess around with concrete types, and since the exposed data types of my package are entirely interfaces, it makes mocking or stubbing calls to my package (example, for testing) incredibly easy.

    For this type of system to work, the methods on the struct (in this case, stringDoer) must be exported, even if the struct itself isn't.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 qtcp 发送数据时偶尔会遇到发送数据失败?用的MSVC编译器(标签-qt|关键词-tcp)
  • ¥15 拓扑学,凸集,紧集。。
  • ¥15 如何扩大AIS数据容量
  • ¥15 单纯型python实现编译报错
  • ¥15 c++2013读写oracle
  • ¥15 c++ gmssl sm2验签demo
  • ¥15 关于模的完全剩余系(关键词-数学方法)
  • ¥15 有没有人懂这个博图程序怎么写,还要跟SFB连接,真的不会,求帮助
  • ¥15 PVE8.2.7无法成功使用a5000的vGPU,什么原因
  • ¥15 keil官网下载psn序列号在哪