go doc笔记

1. go doc命令行使用

go的文档就是注释,采用双斜线和星号的方式
go doc 接受的参数是包名,如果不输入任何参数,那么显示的是当前目录的文档
例子:

/*
提供常用库,有一些常用的方法,方便使用
*/
package lib

//一个加法实现
//返回a+b的值

func Add(a,b int) int {
    return a+b
}
result:
root@john:~/go/src/goxx/ch3/godoc# go doc
package lib // import "goxx/ch3/godoc"

提供常用库,有一些常用的方法,方便使用

func Add(a, b int) int

go doc 指定包名

 root@john:~/go/src/goxx/ch3/godoc# go doc json
package json // import "encoding/json"

Package json implements encoding and decoding of JSON as defined in RFC
7159. The mapping between JSON and Go values is described in the
documentation for the Marshal and Unmarshal functions.

See "JSON and Go" for an introduction to this package:
https://golang.org/doc/articles/json_and_go.html

func Compact(dst *bytes.Buffer, src []byte) error
.........

go doc 查看结构体

    go doc json.Decoder

go doc 查看结构体方法

 

2. 在线浏览文档

  
   1. 安装godoc
       apt install golang-golang-x-tools
   2. 启动服务
      godoc -http=:6060
   3. 在线浏览
      http://127.0.0.1:6060/pkg

 

3. 给文档添加示例代码

   1.示例代码放在一个名为example_test.go文件里。
    2. 定义一个名字是ExampleAdd的函数,参数为空。
    3. 示例的输出采用注视的方式,以//Output:开头,另起一行,每行输出占一行。

   示例;

 

libs.go
/*
提供常用库,有一些常用的方法,方便使用
*/
package lib

//一个加法实现
//返回a+b的值

func Add(a,b int) int {
    return a+b
}

//一个减法的实现
//返回a-b的值
func Sub(a,b int) int {
  return a-b
}

  测试代码:

example_test.go

package lib

import "fmt"

func ExampleAdd() {
    sum := Add(1,2)
    fmt.Println("1+2=",sum)
    //Output:
    //1+2=3
}

func ExampleSub() {
    res := Sub(3,1)
    fmt.Println("3-1=",res)
    //Output:
    //3-1=2
}

   启动服务 godoc -http=:6060,访问http://127.0.0.1:6060/pkg

  go doc笔记_第1张图片

你可能感兴趣的:(golang)