GoDoc示例函数用于类型/结构函数

huangapple go评论90阅读模式
英文:

GoDoc Example function for type/struct functions

问题

问题
我已经编写了一些位于*_test.go文件中的示例函数,以帮助澄清与独立公共函数相关的上下文问题。当为与类型相关联的函数编写示例函数时,显示问题出现了。

示例
以下是我遇到的基本示例。

假设我们在main.go中有一个如下所示的函数:

  1. type Client struct {
  2. user string
  3. ip string
  4. }
  5. func (c *Client) SendNotification(message string) error {
  6. return nil
  7. }

我想在main_test.go中为此创建一个示例函数,如下所示:

  1. func ExampleSendNotification() {
  2. //在这里展示代码
  3. }

VSCode对该特定示例抛出错误,说“ExampleSendNotification引用了未知标识符:SendNotification”。而且,在运行godoc时,它也不会显示为示例。

我还尝试了这种格式:

  1. func (c *Client) ExampleSendNotification() {
  2. //在这里展示代码
  3. }

但是,然后它只是将其从VSCode中删除,并且不会出现。

英文:

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:

  1. type Client struct {
  2. user string
  3. ip string
  4. }
  5. func (c *Client) SendNotification(message string) error {
  6. return nil
  7. }

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

  1. func ExampleSendNotification() {
  2. //Showoff code here
  3. }

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:

  1. func (c *Client) ExampleSendNotification() {
  2. //Showoff code here
  3. }

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

答案1

得分: 3

我在写完这段话之前找到了答案。我觉得还是发出来给其他人看看。

诀窍是写成Example[Type]_[Method]的形式,所以在我的例子中,应该是这样写:

  1. func ExampleClient_SendNotification() {
  2. //这里是展示代码
  3. }
英文:

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:

  1. func ExampleClient_SendNotification() {
  2. //Showoff code here
  3. }

huangapple
  • 本文由 发表于 2023年2月8日 04:23:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/75378617.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定