packages in golang

p

 A package is nothing but a directory with some code files, which exposes different variables and/or functions from a single point of reference

To be honest we used library and its functions many time. Here! look at this program:

package main

import (
	"fmt"
)

func main() {
	var num  = [5]int {1, 2, 4, 3, 5}

	fmt.Println(len(num))
}

Here we used len() function from Go’s standard library. Thats cool but what actually is this magic thing called packages?

If a program is part of the main package, then go install will create a binary file; which upon execution calls main function of the program. If a program is part of package other than main, then a package archive file is created with go install command

Now we already know this. So lets create our new package.

Go to your workspace and create a new folder /src. for me its under ~/go/src

If a package does not contain a file with main package declaration, then Go creates a package archive (.a)file inside pkg directory.

package hi

import "fmt"

func main() {
	fmt.Println("hi from main!")
}
(Ignore the other packages)

But we don’t want to create archive file. we want to use that inside our other packages.

So lets delete the main() and re-write it.

package mypack

var name string = "filename: hello.go"
var Shout string = "hello from " + name

now lets use these variables inside our another package.

//hi.go
package main

import "fmt"
import "mypack"

func main() {
	fmt.Println("hi from main!")
	fmt.Println(mypack.Shout)
}

Hey! but what if I tried to use the variabe name

This happens because name is not exportable variable. If you want to export a variable the first letter of the variable should be caps. Yes. Then it will work.

using 3rd party libraries

Go to https://godoc.org/

choose which package you want to use.

For me I choosed this package https://godoc.org/github.com/google/uuid

So run this command.

This will install that package under /src

So now lets use this:

package main

import (
    "fmt"
    "github.com/google/uuid"
)

func main() {
    id := uuid.New()
    fmt.Println(id.String())
}

See it worked!

And thats all for todays article.

Happy coding!

About the author

vigneshwar

Add comment

Leave a Reply

By vigneshwar

Most common tags

%d bloggers like this: