Getting Started with Go

I just installed the Go programming language and I’m going to start fiddling with it. On their homepage they have online interperer that you can play around with. The iterperter comes with several pre-built codes that you can tinker with. One of these codes was a fibinacii sequence generator so I decided that this was a good choice to see how to do some basic stuff in Go.

Here is the original code.

package main

// fib returns a function that returns
// successive Fibonacci numbers.
func fib() func() int {
	a, b := 0, 1
	return func() int {
		a, b = b, a+b
		return a
	}
}

func main() {
	f := fib()
	// Function calls are evaluated left-to-right.
	println(f(), f(), f(), f(), f())
}

I really liked this one, anyway every time the variable assigned to the Fibonacci function is called the next Fibonacci number is found. The output will be, “1 1 2 3 5” if you add another f() into the println statement the code will then be “1 1 2 3 5 8”. So the first thing I wanted to learn how to write in Go was a for loop so I made a basic for loop that will generate a Fibonacci sequence “1 1 2 3 5 “. Here is how I reworked the main function.

func main() {
	f := fib()
	// Function calls are evaluated left-to-right.
	for i := 0; i < 5; i++ {
	   print(f(), " ")
	}	
}

This version looks very “C” like and there are a few other ways it can be rewritten. This next version does the exact same thing as the prior for loop but the variable isn’t initialized or incremented in the for loop declaration. This one kinda works like a while loop.

func main() {
	f := fib()
	// Function calls are evaluated left-to-right.
	i := 0
	for; i < 5;{
		print(f(), " ")
		i++
	}
}

If you’re somewhat OCD like me the extra space at the end of the Fibonacci sequence will drive you crazy. Lets fix this with a simple if statement.

func main() {
	f := fib()
	// Function calls are evaluated left-to-right.
	i := 0
	for; i < 5;{
                // This is a dumb hack
		if( i < 4 ){
			print(f(), " ")
		} else {
			print(f())
		}
		i++
	}
}

As you can see I haven’t done too much with this language yet but check out the source code for the Peg Solitaire Solver, that one looked pretty cool too me.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s