Search code examples
gocommentsdocumentation

Get go doc to follow a type alias and function variable


I am developing a package that has nested packages to assist in organizing my code. My top level package exposes some "aliases" of common functionality nested inside of the other packages like many other projects do. For example: https://github.com/cloudevents/sdk-go/blob/main/v2/alias.go

Everything works great. However, the go docs do not seem to become attached to the alias, and only are on the original definition.

Here's a minimal example:

// NEW FILE: <module_root>/models/models.go
package models

type MyType struct {
   // comment
   num int

   // other comment
   text string
}

// Repeats MyType.text MyType.num times
func (t *MyType) Repeat() string {
    rStr := ""
    for i := 0; i < t.num; i++ {
         rStr += t.text
    }
    return rStr
}


// Create MyType with specified arguments
func NewMyType(num int, text string) MyType {
    return MyType{
        num: num,
        text: text,
    }
}

// NEW FILE: <module_root>/alias.go
package mymodule

import models


type MyType = models.MyType

var NewMyType = models.NewMyType

Interestingly, the go doc seems to show that MyType has the method Repeat(), but does not show it's struct definition and the associated comments like it does when looking at models.MyType. Additionally, only the function signature is shown for NewMyType, and not the go docs that exist on models.NewMyType.

How can I expose the already defined go docs on this type alias and "function alias" var?

I have also tried looking through the documentation about go docs and have not seen any note about this or a way to "copy"/"forward" a go doc comment.


Solution

  • Aliases are designed for codebase refactoring, so you'll have your documentation at the new, refactored code and replace the old, potentially deprecated code with an alias.

    In your case mymodule would be the old module used by existing legacy code and models the new package with documentation intended to be used by new code.

    So there is no “forwarding”, and “backwarding” documentation is not intended - new code should use the newly moved packages.

    What would be helpful is to add additional documentation like “deprecated, use models.MyType at the alias mymodule.MyType.