gogodoc

GoDoc Example function for type/struct functions


Problem

I have written some example functions located in a *_test.go file to help clarify context for standalone public functions without issue. The problem on displaying comes when writing example functions for functions tied to a type.

Example

Here's a basic example of what I'm encountering.

Say we have a function in main.go like below:

type Client struct {
  user string
  ip string
}

func (c *Client) SendNotification(message string) error {
  return nil
}

I want to create an example function for such in main_test.go, like below

func ExampleSendNotification() {
  //Showoff code here
}

VSCode throws an error for that specific example, saying "ExampleSendNotification refers to unknown identifier: SendNotification". Also, it just does not appear as an example when running the godoc.

I've also tried this format:

func (c *Client) ExampleSendNotification() {
  //Showoff code here
}

But then it just removes it as a test in VSCode, and doesn't appear


Solution

  • I found the answer just as I was finishing writing this. Thought I would still post for anybody else.

    The trick is writing Example[Type]_[Method], so practically in my example, that would look like:

    func ExampleClient_SendNotification() {
      //Showoff code here
    }