Skip to content

Commit

Permalink
Go构建可复用的包(导包)代码练习
Browse files Browse the repository at this point in the history
SOYANGA committed Sep 25, 2019
1 parent 871d141 commit af9a6b5
Showing 2 changed files with 47 additions and 0 deletions.
20 changes: 20 additions & 0 deletions code/ch14/client/package_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package client

//会引入我们GetFibonacci所在的本地包
import (
"ch14/series"
"testing"
)

func TestPackage(t *testing.T) {
t.Log(series.GetFibonacci(5))
//t.Log(series.square(5))
}

//执行结果 重名的init方法被执行两次
//init1
//init2
//=== RUN TestPackage
//--- PASS: TestPackage (0.00s)
//package_test.go:10: [1 1 2 3 5] <nil>
//PASS
27 changes: 27 additions & 0 deletions code/ch14/series/my_series.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package series

import "fmt"

func init() {
fmt.Println("init1")
}

func init() {
fmt.Println("init2")
}



//大写字母开头包外可以访问
func GetFibonacci(n int) ([]int, error) {
fibList := []int{1, 1}
for i := 2; /*短变量声明*/ i < n; i++ {
fibList = append(fibList, fibList[i-2]+fibList[i-1])
}
return fibList, nil
}

//小写字母开头包外不能访问
func square(n int) int {
return n * n
}

0 comments on commit af9a6b5

Please sign in to comment.