功能函数
// queue.go
package queue
// Queue : A FIFO queue.
type Queue []int
// Push : Pushes the element into the queue.
// e.g. q.Push(123)
func (q *Queue) Push(v int) {
*q = append(*q, v)
}
// Pop : Pops element from head.
func (q *Queue) Pop() int {
head := (*q)[0]
*q = (*q)[1:]
return head
}
// IsEmpty : Returns if the queue is empty or not.
func (q *Queue) IsEmpty() bool {
return len(*q) == 0
}
测试函数
注意点!
- 文件命名方式 (原文件名)_test.go
- Test 函数命名方式 Test(待测试函数名),参数 t *testing.T
- Benchmark 测试函数(测试性能) 参数 b *testing.B
- Example 测试函数,期望结果【通过注释方式,以 Output 开头】
// queue_test.go
// 注意文件命名方式,后面加 _test
package queue
import (
"fmt"
"testing"
)
// 注意函数命名方式 Example 函数
// Output 写自己期望的输出
func ExampleQueue_Pop() {
q := Queue{1}
q.Push(2)
q.Push(3)
fmt.Println(q.Pop())
fmt.Println(q.Pop())
fmt.Println(q.IsEmpty())
fmt.Println(q.Pop())
fmt.Println(q.IsEmpty())
// Output:
// 1
// 2
// false
// 3
// true
}
// 表格测试函数:数据与测试逻辑分离
// 注意函数命名方式 Test 函数
// 参数 t *testing.T
// Benchmark 测试函数是测试性能,此处没有写,参数为 b *testing.B
func TestQueue_Pop(t *testing.T) {
data := []struct {
example Queue
expect int
}{
{[]int{1, 2, 3}, 1},
{[]int{2, 35, 4}, 2},
}
for _, tt := range data {
actual := tt.example.Pop()
if actual != tt.expect {
t.Errorf("Expect: %d, Actual: %d, Error!", tt.expect, actual)
}
}
}
文档记录
go doc 查看
# 不加参数,会打印当前包中的数据结构
$ go doc
package queue // import "queue"
type Queue []int
# 可以指定函数,将会打印此函数的介绍信息(就是函数功能的注释信息)
# 可以通过更改此函数的注释,改变打印的内容
$ go doc Pop
package queue // import "."
func (q *Queue) Pop() int
Pop : Pops element from head.
godoc 网页查看
优势:
- 不仅可以展示 go get 下载的包
- 而且自己编写的函数,也会以文档形式展示,见下面截图
# 首先下载包
$ go get golang.org/x/tools/cmd/godoc
# 开启端口进行展示 指定了 6060 端口
$ godoc -http=:6060
# 访问
localhost:6060