Skip to content

Instantly share code, notes, and snippets.

@xd547
Created March 19, 2014 13:53
Show Gist options
  • Select an option

  • Save xd547/9642094 to your computer and use it in GitHub Desktop.

Select an option

Save xd547/9642094 to your computer and use it in GitHub Desktop.
Writing, building, installing, and testing Go code
# from https://www.youtube.com/watch?v=XCsL89YtqCs
mkdir gocode
export GOPATH=$HOME/gocode
cd gocode
mkdir -p src/github.com/xd547
mkdir hello
cd hello
# create hello.go
# see hello.go below
go install
ls ~/gocode/bin
# hello
~/gocode/bin/hello
# Hello, new gopher!
cd ..
mkdir string
cd string
# create string.go
# see string.go below
go build
go install
ls ~/gocode/pkg/darwin_amd64/github.com/xd547
# string.a
cd ../hello
# edit hello.go
# see hello_new.go
go install
hello
# !rehpog wen ,olleH
cd ../string
# edit create string_test.go
# see string_test.go below
go test
# --- FAIL: Test (0.00 seconds)
# string_test.go:16: Reverse("Hello, 世界") == "\x8c\x95疸\xe4 ,olleH", want "界世 ,olleH"
# FAIL
# exit status 1
# FAIL github.com/xd547/string 0.009s
#
# edit string.go
# see string_new.go
go test
# PASS
# ok github.com/xd547/string 0.008s
package main
import "fmt"
func main() {
fmt.Println("Hello, new gopher!");
}
package main
import (
"fmt"
"github.com/xd547/string"
)
func main() {
fmt.Println(string.Reverse("Hello, new gopher!"));
}
package string
func Reverse(s string) string {
b := []byte(s)
for i := 0; i < len(b)/2; i++ {
j := len(b)-i-1
b[i], b[j] = b[j], b[i]
}
return string(b)
}
package string
func Reverse(s string) string {
b := []rune(s)
for i := 0; i < len(b)/2; i++ {
j := len(b)-i-1
b[i], b[j] = b[j], b[i]
}
return string(b)
}
package string
import "testing"
func Test(t *testing.T) {
var tests = []struct {
s, want string
}{
{"Backward", "drawkcaB"},
{"Hello, 世界", "界世 ,olleH"},
{"", ""},
}
for _, c := range tests {
got := Reverse(c.s)
if got != c.want {
t.Errorf("Reverse(%q) == %q, want %q", c.s, got, c.want)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment