Thursday, June 18, 2015

Intro to Go Programming Package Creation

Go tools requires code organization in specific way for easy build, deploy your go code. The following section describes the process.

1) Create a specific directory $HOME/mygo
2) Set the environment variable GOPATH=$HOME/mygo
3) Create a unique namespace mkdir $GOPATH/src/

Develop your code inside the namespace

mkdir $GOPATH/src/
cd $GOPATH/src/
>> write your hello.go

build and install your hello.go with go install command in the current directory the binary will be installed in $GOPATH/bin directory

Lets create our own package to by used by other go program such as hello.go

mkdir $GOPATH/src/
cd $GOPATH/src/
>> write your string.go

package string

func Reverse(s string) string {
        b := []byte(s)
        for i:=0; i < len(s)/2; i++ {
                j := len(s)-i-1
                ch := b[i]
                b[i] = b[j]
                b[j] = ch
        return (string(b))

run go install in the string directory to create package string the output string.a will appear in 

Now lets use our string package in our hello.go

cd $GOPATH/src/

package main

import (

func main() {
        fmt.Println(string.Reverse("Hello World!!"))

build the hello.go with go install


Let's write test program to test the package
cd $GOPATH/src/
vi string_test.go

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)



run go test (If no error great, else fix the issue)

No comments:

Post a Comment