開発環境
- macOS High Sierra - Apple (OS)
- Emacs (Text Editor)
- Go (プログラミング言語)
Introducing Go: Build Reliable, Scalable Programs (Caleb Doxsey (著)、O'Reilly Media)のChapter 8.(Packages)、Exercises(No. 1811)1、2、3、4.を取り組んでみる。
コード(Emacs)
package main import ( "fmt" // 3. making pckage alias m "introducing-go/chapter8/math" ) func main() { xs := []float64{1, 2, 3, 4} min := m.Min(xs) max := m.Max(xs) fmt.Println(xs) fmt.Println("Min:", min) fmt.Println("Max:", max) }
~/go/src/introducing-go/chapter8/math/math.go(GOPATH="~/go")
// Package math provides Min and Max functions that find the minimum and maximum // values in a slice of float64s package math // Finds the minimum values in a slice of float64s func Min(xs []float64) float64 { m := xs[0] for _, x := range xs[1:] { if x < m { m = x } } return m } // Finds the maxmum values in a slice of float64s func Max(xs []float64) float64 { m := xs[0] for _, x := range xs[1:] { if x > m { m = x } } return m }
入出力結果(Terminal)
$ go run sample1.go [1 2 3 4] Min: 1 Max: 4 $ go doc introducing-go/chapter8/math package math // import "introducing-go/chapter8/math" Package math provides Min and Max functions that find the minimum and maximum values in a slice of float64s func Max(xs []float64) float64 func Min(xs []float64) float64 $ go doc introducing-go/chapter8/math Min func Min(xs []float64) float64 Finds the minimum values in a slice of float64s $ go doc introducing-go/chapter8/math Max func Max(xs []float64) float64 Finds the maxmum values in a slice of float64s $
作法じゃなくて仕様なのかも。(?)
— kamimura (@mkamimura) 2018年8月6日
パッケージの関数(メソッド)が大文字で始まるのは、仕様だったみたい。(大文字だとパッケージ外で使える、小文字だとパッケージ内でのみ使える。)
packageの関数(メソッド)、頭文字が大文字か小文字かで公開か非公開か決まることが分かって、日本語名の関数の場合どうなるか試してみたら、日本語のメソッド名は使えるけど公開には出来ないみたい。(func 最大()は非公開で、func A最大()とすれば公開に出来た。)
0 コメント:
コメントを投稿