Learning the Go Programming Language, First Steps

Language Features

Go is Google's attempt to mate system languages like C, with more theoretically pleasing languages like Haskell. Its features include:

  • Easy concurrency
  • Python-like whitespace usage.
  • Strong, static typing
  • Functions are first class datatypes
  • Functional programming features

Hello World: Code

package main
import "fmt"
func main() {
	fmt.Println("Hello World!")
}

Hello World

The important things to note about this small program are:

  • This is basically a void function
  • Packaging syntax and the packages used.

The canonical version of Hello World for Go uses unicode characters, I have restricted myself to ASCII characters for portability of this article.

Basic Program: Code

package main

import "fmt"

func fib(n int) int {
	if n == 0 {
		return 0
		}
	if n == 1 {
		return 1
	}
	return fib(n-1) + fib(n-2)
}

func main() {
	fmt.Printf("%d",fib(21))
}

Basic Program

Note here:

  • The 'reverse' type declarations
  • The If statement.syntax (the same syntax is used for loops)

Concurrency: Code

package main

import "fmt"

func fib(out chan<- int, n int) {
	last := 0
	this := 1
	temp := 0
	if n <= 1 {
		out <- n
		return
	}
	for i := 2; i <= n; i++ {
		temp = this
		this = last + this
		last = temp
	}	
	out <- this
}

func main() {

	var ch [10]chan int
	
	for i := 0; i < 9; i++ {
		ch[i] = make(chan int)
		go fib(ch[i], i*3)		
	}
	for i := 0; i < 9; i++ {
		fmt.Printf("%d: %d\n", i*3, <-ch[i])
	}
}

Concurrency

Quite a bit new here, but its mostly trivial syntax.

make(): Allocates special types, like slices, maps and channels. I discuss channels below. golang uses new() for 'normal' allocation.

Channels: channels are a reference type, with single directional properties, somewhat like c++ streams.

There is a flaw in this code, we only ensure that ch[i] has received a value, not that it has received the final value, As an exercise, fix this.

Further Reading

We have only scratched the surface of Go's features. The purpose of this article was to give you a taste, from grounds that are widely familiar.

Unfortunately, there is but one (somewhat poor) book on the Go Programming Language that is currently in publication. The best additional resources I can direct you to are at the golang.org community.

Comments

No comments yet.

    Sign in or sign up and post using a HubPages Network account.

    0 of 8192 characters used
    Post Comment

    No HTML is allowed in comments, but URLs will be hyperlinked. Comments are not for promoting your articles or other sites.


    Click to Rate This Article
    working