ObjectHunter
Hunting and gathering in the JEE landscape

I am Frank, a freelance Java developer specialized in backend development from south western germany.

Playing with Google's Go programming language

posted by fas on 2010-06-17 . Tagged as programming, example, go

Go seems to be a nice language and this simple example shows some of Go's capabilities and idiosyncrasies:

  • multiple return types
  • functions start with an upper case letter while packages start with a lower case letter, which looks just wrong to my Java eyes ;)
  • the opening bracket "{" after an IF/FOR statement has to be on the same line
  • return types stand in parethesis after the function name and argument definition
  • type comes after the variable name (var i uint64=12): a variable of type uint64 named i with a value of 3
  • theres no long type instead there are int, int32 and int64 and the corresponding unsigned types uint, uint32 and uint64. This is logical. I like that ;)
  • command line arguments are not part of main's signature, but get parsed by the flag package


IsPrime.go:

package main

import "fmt"
import "flag"
import "strconv"
import "math"

func main() {
    flag.Parse()
    number,err := strconv.Atoui64(flag.Arg(0))
    if err != nil {
        fmt.Printf("Error %s\n",err.String())
        return
    }
    fmt.Printf("checking %d for primality...\n",number)
    fmt.Printf("%d primality: %t\n",number,isPrime(number))
}

func isPrime(number uint64) (bool) {
    if number == 2 {
        return true
    }
    if number % 2 == 0 {
        return false
    }
    max := uint64(math.Sqrt(float64(number)))
    var i uint64
    for i=3;i<max;i+=2 {
        if number % i == 0 {
            return false
        }
    }
    return true
}


Compilation (Example uses the 6g 64-bit compiler/linker)

#$ 6g IsPrime.go
#$ 6l IsPrime.6
#$ ./IsPrime 62659
checking 62659 for primality:
62659 primality: true
#$ 



have fun playing with this blazingly fast compiling language yourself!

Tags: programming, example, go