学习一门新语言我最喜欢用的例子是斐波那契数列的计算,go的相关代码摘抄自《the way to go》:

package main

import (
	"fmt"
	"time"
)

const LIM = 10000

var fibs [LIM]uint64

func main() {
	var result uint64 = 0
	start := time.Now()
	for i := 0; i < LIM; i++ {
		result = fibonacci(i)
		fmt.Printf("fibonacci(%d) is: %d\n", i, result)
	}
	end := time.Now()
	delta := end.Sub(start)
	fmt.Printf("longCalculation took this amount of time: %s\n", delta)
}
func fibonacci(n int) (res uint64) {
	// memoization: check if fibonacci(n) is already known in array:
	if fibs[n] != 0 {
		res = fibs[n]
		return
	}
	if n <= 1 {
		res = 1
	} else {
		res = fibonacci(n-1) + fibonacci(n-2)
	}
	fibs[n] = res
	return
}

首先这是一段标准的go递归函数实例,每一句都很清晰,相信你很容易看懂,在1cpu * 3GHz的虚拟机环境下,go计算10000个斐波那契数列花了111ms,非常优秀的性能。