Thursday, March 1, 2012

Go fib

I've been having fun with a new programming language called Go, developed by Rob Pike and friends at Google (video). Somehow I missed hearing about it until now. I'm not leaving my true love, Python, but there's a lot to like about Go as a replacement for C and C++.

Go has

  • garbage collection, so there are no worries about managing memory
  • no classes, but simply attaches methods to types
  • a simple syntax compared to C---eliminating most semicolons
  • much less complexity than C++
  • goroutines to launch parallel processes that communicate using channels
  • maps and string support, and slices as a kind of resizable array
  • multiple return values from a function
  • combined var declaration and assignment with type of rhs
  • pointers but no pointer arithmetic
  • the ability to construct and return a local variable from a function.
  • great docs, is compiled, and fast.

    Go has interfaces, which I don't understand very well, but they can be used to give polymorphic behavior.

    Here is a simple, familiar Go program using a goroutine and a channel. Notice that the type declaration comes after the variable name, and the arrow symbol for flow into and out of the channel, c.

    package main
    
    import "fmt"
    
    func fib(c chan int) {
        var a, b int = 1, 0
        for {
            c <- a
            a, b = a + b, a
        }
    }
    
    func main() {
        c := make(chan int)
        go fib(c)
        for i := 1; i < 12; i++ {
            f := <- c
            fmt.Println(f)
        }
    }
    fib() will generate values as long as we want, similar to a Python generator. Output:
    1
    1
    2
    3
    5
    8
    13
    21
    34
    55
    89
    I found a Go "bundle" for TextMate here.