Go Cookbook
上QQ阅读APP看书,第一时间看更新

How to do it...

These steps cover writing and running your application:

  1. From your terminal/console application, create and navigate to the chapter3/math directory.
  2. Copy tests from https://github.com/agtorre/go-cookbook/tree/master/chapter3/math or use this as an exercise to write some of your own code.
  3. Create a file called math.go with the following contents:
        package math

import (
"fmt"
"math"
)

// Examples demonstrates some of the functions
// in the math package
func Examples() {
//sqrt Examples
i := 25

// i is an int, so convert
result := math.Sqrt(float64(i))

// sqrt of 25 == 5
fmt.Println(result)

// ceil rounds up
result = math.Ceil(9.5)
fmt.Println(result)

// floor rounds down
result = math.Floor(9.5)
fmt.Println(result)

// math also stores some consts:
fmt.Println("Pi:", math.Pi, "E:", math.E)
}
  1. Create a file called fib.go with the following contents:
        package math

import "math/big"

// global to memoize fib
var memoize map[int]*big.Int

func init() {
// initialize the map
memoize = make(map[int]*big.Int)
}

// Fib prints the nth digit of the fibonacci sequence
// it will return 1 for anything < 0 as well...
// it's calculated recursively and use big.Int since
// int64 will quickly overflow
func Fib(n int) *big.Int {
if n < 0 {
return nil
}

// base case
if n < 2 {
memoize[n] = big.NewInt(1)
}

// check if we stored it before
// if so return with no calculation
if val, ok := memoize[n]; ok {
return val
}

// initialize map then add previous 2 fib values
memoize[n] = big.NewInt(0)
memoize[n].Add(memoize[n], Fib(n-1))
memoize[n].Add(memoize[n], Fib(n-2))

// return result
return memoize[n]
}
  1. Create a new directory named example.
  2. Navigate to example.
  1. Create a file main.go with the following contents; be sure to modify the math import to use the path you set up in step 2:
        package main

import (
"fmt"

"github.com/agtorre/go-cookbook/chapter3/math"
)

func main() {
math.Examples()

for i := 0; i < 10; i++ {
fmt.Printf("%v ", math.Fib(i))
}
fmt.Println()
}
  1. Run go run main.go.
  2. You could also run:
      go build
./example

You should see the following output:

      $ go run main.go
5
10
9
Pi: 3.141592653589793 E: 2.718281828459045
1 1 2 3 5 8 13 21 34 55
  1. If you copied or wrote your own tests, go up one directory and run go test. Ensure that all tests pass.