2015年10月16日金曜日

Go lang "Hello, world" on Mac OS X

This is a sample Go app for "Hello, world".

1) get "Apple OS X" install package from download page.
https://golang.org/dl/

2) Install gox.x.x.darwin-amd64.pkg on your Mac.

3) make code dir and set $GOPATH
$ mkdir ~/gocode
$ echo 'export GOPATH=$HOME/gocode' >> ~/.bashrc
$ source $HOME/.bashrc
4) make "Hello, world."
$ mkdir -p ~/gocode/src/hello
$ cd ~/gocode/src/hello
$ emacs hello.go
package main

import "fmt"

func main() {
 fmt.Printf("Hello, world.\n")
}

$ go install
$ tree ~/gocode
/Users/yako/gocode
├── bin
│   └── hello
└── src
    └── hello
        └── hello.go

3 directories, 2 files

$ $GOPATH/bin/hello
Hello, world.
5) make library.
$ mkdir ~/gocode/src/stringutil
$ cd ~/gocode/src/stringutil
$ emacs reverse.go
// Package stringutil contains utility functions for working with strings.
package stringutil

// Reverse returns its argument string reversed rune-wise left to right.
func Reverse(s string) string {
 r := []rune(s)
 for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 {
  r[i], r[j] = r[j], r[i]
 }
 return string(r)
}

$ cd ~/gocode/src/hello
$ emacs hello.go
package main

import (
       "fmt"

       "stringutil"
)

func main() {
     fmt.Printf(stringutil.Reverse("!oG ,olleH"))
}

$ go install
$ tree ~/gocode
/Users/yako/gocode
├── bin
│   └── hello
├── pkg
│   └── darwin_amd64
│       └── stringutil.a
└── src
    ├── hello
    │   ├── hello.go
    └── stringutil
        └── reverse.go

6 directories, 5 files

$ $GOPATH/bin/hello
Hello, Go!
6) make reverse test.
$ cd ~/gocode/src/stringutil
$ emacs reverse_test.go
package stringutil

import "testing"

func TestReverse(t *testing.T) {
 cases := []struct {
  in, want string
 }{
  {"Hello, world", "dlrow ,olleH"},
  {"Hello, 世界", "界世 ,olleH"},
  {"", ""},
 }
 for _, c := range cases {
  got := Reverse(c.in)
  if got != c.want {
   t.Errorf("Reverse(%q) == %q, want %q", c.in, got, c.want)
  }
 }
}

$ tree ~/gocode
/Users/yako/gocode
├── bin
│   └── hello
├── pkg
│   └── darwin_amd64
│       └── stringutil.a
└── src
    ├── hello
    │   └── hello.go
    └── stringutil
        ├── reverse.go
        └── reverse_test.go

6 directories, 5 files

$ go test stringutil
ok   stringutil 0.006s

See also.

How to Write Go Code
https://golang.org/doc/code.html

Top image from Yuko Honda Today's latte, celebrating Go version 1!
The Go gopher was designed by Renee French. http://reneefrench.blogspot.com/