9
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[メモ書き] GoでTDD風な感じでライブラリを作って公開てのをとりあえずやってみる

Last updated at Posted at 2015-05-10

今回は素数を生成するPrime というライブラリをGithubに公開する流れを例にとります.

フォルダを作る

特に命名はかっちりと決まっていませんが

githubに公開する場合は $GOPATH/src/github.com/ユーザー名/ライブラリ名 が良い習慣だと思います.

mkdir -p $GOPATH/src/github.com/gogotanaka/prime

ファイルを作る. testファイルの命名は xxxx_test.go

cd $GOPATH/src/github.com/gogotanaka/prime 

touch prime.go, prime_test.go

testを書いてみる

go の標準のテストはif文を駆使して落とすように書く、落ちなかったら成功.

割と好みだけど冗長

prime_test.go
package prime

import "testing"

func TestGet(t *testing.T) {
  if p := Get(1); p != 2 {
    t.Errorf("Expect: Get(1) is 2, Actual: %d", p)
  }

  if p := Get(5); p != 11 {
    t.Errorf("Expect: Get(5) is 11, Actual: %d", p)
  }
}

とりあえずこんなのを書いてみる.

prime.go
package prime

func Get(n int) int {
	return n
}

テストを走らせる

go test
--- FAIL: TestGet (0.00s)
	prime_test.go:7: Expect: Get(1) is 2, Actual: 1
	prime_test.go:11: Expect: Get(5) is 11, Actual: 5
FAIL
exit status 1
FAIL	github.com/gogotanaka/prime	0.005s

おお、

実装

(TDDの下りは省略)

以下が完成したコード

prime.go
package prime

func Get(n int) int {
	c := make(chan int)
	var p int
	go gen(c)
	for i := 1; i <= n; i++ {
		p = <-c
		c1 := make(chan int)
		go filter(c, c1, p)
		c = c1
	}

	return p
}

func gen(c chan<- int) {
	for i := 2; ; i++ {
		c <- i
	}
}

func filter(in <-chan int, out chan<- int, p int) {
	for {
		i := <-in
		if i%p != 0 {
			out <- i
		}
	}
}
go test
PASS
ok  	github.com/gogotanaka/prime	0.005s

いいね!

github にpush

git init
git add -A .; git commit -m 'Init'
git push origin master

使えるか試してみる

go get github.com/gogotanaka/prime 

ls $GOPATH/pkg/darwin_amd64/github.com/gogotanaka 
#=> prime.a

おお!試してみよう

mkdir /tmp/try_prime; cd /tmp/try_prime; touch main.go
main.go
package main

import (
    "fmt"
    "github.com/gogotanaka/prime"
)

func main() {
    fmt.Println(prime.Get(5))
}

go run main.go 
#=> 11

使えてる!!

9
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?