Search code examples
goprivategodoc

Documenting public methods on private structs via Godoc in Go


I have a private struct (actually more than one, I simplified a bit for this example) which I have a public function on, that satisfies a public interface. This struct is created via a factory method (NewX-style):

package godocprivate

type PublicInterface interface {
    PublicFunction()
}

type privatestruct struct {
}

func NewPublic() *privatestruct {
    ps := &privatestruct{}
    return ps
}

// PublicFunction does something to be documented
func (self *privatestruct) PublicFunction() {
}

I cannot make the factory method return the public interface, because there are other interfaces to be satisfied by the returned value, in my project.

I do want to document PublicFunction() via godoc, but because it is on a private struct, it does not show up:

This is how Godoc of the above looks like

Is there any way, trick, workaround, etc. to make privatestruct.PublicFunction() visible in Godoc?

My actual use case is even more severe: I do have more than one private struct. All of them satisfy PublicInterface, but the inner workings of their respective PublicFunction-implementations differ, hence could their documentations need to be different, too...


Solution

  • PublicFunction uses PublicStruct whose private fields will be private with private documentation. For example,

    package godocprivate
    
    type PublicInterface interface {
        PublicFunction()
    }
    
    type privatestruct struct {
    }
    
    // PublicStruct is something to be documented except for private fields
    type PublicStruct struct {
        privatestruct
    }
    
    func NewPublic() *PublicStruct {
        ps := &PublicStruct{}
        return ps
    }
    
    // PublicFunction does something to be documented
    func (p *PublicStruct) PublicFunction() {
    }
    

    When PublicStruct is created it initially has zero values for each field. If that's not enough, introduce a factory boolean. For example,

    package godocprivate
    
    type PublicInterface interface {
        PublicFunction()
    }
    
    type privatestruct struct {
    }
    
    // PublicStruct is something to be documented except for private fields
    type PublicStruct struct {
        factory bool
        privatestruct
    }
    
    func NewPublic() *PublicStruct {
        ps := &PublicStruct{factory: true}
        return ps
    }
    
    // PublicFunction does something to be documented
    func (p *PublicStruct) PublicFunction() {
        if !p.factory {
            panic("Use NewPublic")
        }
    }