Tuesday, April 17, 2012

Compiling multiple source files with go

Go1 the first version of go uses the '$go build' command to build programs. The best way to explain how you can compile a go program spread over multiple files is by an example.

1. Create a folder "random"
$mkdir random

2. Create a go package called "random" inside the "random" folder. We are going to use 'vim' as our editor in this example. Replace 'vim' with your favorite editor.
$vim random/random.go

3. Paste the following code in it
package random

func FirstName() string {
 return "Alice in wonderland"
}

4. Create the file for the main program
$vim names.go

5. Paste the following code in it
package main

import "fmt"
import "./random"

func main() {
 n := random.FirstName()
 fmt.Println(n)
}

- Note the 'import "./random"' statement which imports the random package which we created above.
- Note the 'package main' statement. Since this is the main file of our program we use 'package main', but in the above 'random/random.go' package we will use 'package random'
- Note how we call the 'random.FirstName()'


6. Now build the program using
$go build names.go
This will automatically compile the random package along with the main program. After running this command you will see a binary executable file called 'names' in the current directory.
$ls
names  names.go  random

7. Run the program
$./names
Alice in wonderland

Alternatively you can directly run the program using :
$go run names.go
Alice in wonderland

Thursday, April 5, 2012

Difference between new() and make()

There are two basic types in Go :

Value types - They contain the actual data. They are char, bool, int, float, string. These types are stored on stack.

Reference types - They contain the memory address which points to actual data. Examples are slice, maps and channels. These types are stored on heap.

The new() function is useful only for value types. It returns the address where the type T is stored in the heap.

Since the reference types are already addresses we use make() function which returns the value of type T.

In short :
- new() is used for value types and make() is used for reference types.
- new() returns a address and make() returns a value.

If we do a new() on reference types it returns a address, which itself points to a address where the type T is stored.

Consider the following slice example :
s1 := new([]int)
This returns the address that points to a slice. Since slice is a reference type, the slice itself is a address which points to where the actual data is stored. Thats why we use
s1 := make([]int, 10)
This returns the actual slice.