Sunday, September 11, 2011

Create a new GO package

In this tutorial we will learn how to create a new GO package similar to "fmt" and others. There are several advantages of packages. Firstly, if your go application ranges over several files and functionality, its better to have those in different packages. Secondly, if want to publish your own set of go APIs you can simply package them and make available to public.

Lets create a simple GO package with only one function in it.
1. Write a go program.

package file

func TestFunc(name string) string{
        if(name == ""){
           return "Not a valid name"     
        return "TestFunc"+name

2. Create a directory naming the package name in "src" folder of GO installation directory.
    Ex: Save this file in C:/go/src/file folder as file.go; as package name mentioned in above program.

3. TestFunc function must start with capital letters since its a convention in GO language that if the function name starts with capital letter then only it will be visible outside the package.

4.Now your package is ready. You just need to install the package. Following are the set of commands you need to follow to install it.

Go to c:/go/src/file and execute following commands.

set gopath=c:\go            (base directory where you put your package)

set gopath                         (confirm the gopath is set or not)

exit from command prompt.

open command prompt again.

Go to c:/go/src/file and execute following command to install the package.

goinstall -make=false .

Now your package is installed and ready for use.

Let's write a program to test it.

package main


func main(){
       fmt.Printf(file.TestFunc("Anuj Verma"))

Save this file as test.go in any directory. You have your "file" package available with you.
Execute following commands to run it.

8g test.go              To compile it. 

8l test.8               To link it.

8.out.exe               To run it.

This is how we can create our own packages in GO.

Let's GO

No comments:

Post a Comment