Basic Examples

For each example, there is a run link above the code sample that takes you to the Go Playground, where you can run the program and modify it to see what happens.

Hello, World

run

package main

import "fmt"

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

Hello, World, annotated

The lines beginning with // are comments: the Go compiler ignores them and they don't have any effect when the program runs.

run

// Annotated Hello, World program.

// You need a main package if you're going to run this
// as a standalone program.
package main

// We're going to use the fmt library of code.
import "fmt"

// We also need a function called main().
// The main function does not take any parameters.
// We'll deal with parameters later.
func main() {
    // Use the Printf function from the fmt package to print a string.
    fmt.Printf("Hello, World!\n")
}

An annotated binary search program that visualizes the search.

run

package main

import (
	"fmt"
	"sort"
	"time"
)

// Visualizes the binary search steps.
func vis(length, qval, low, mid, high int) {
	// Probably can optimize this eventually.
	// No need to create pic each time vis is called.
	pic := make([]byte, length, length)
	// Show visual.
	for i := 0; i < length; i++ {
		pic[i] = '.'
	}
	pic[low] = '|'
	pic[high] = '|'
	pic[mid] = 'm'
	if mid == qval {
		pic[mid] = '*'
	}
	fmt.Printf("%s\n", string(pic))
}

// This is the binary search itself.
// Simple binary search of an int slice.
// Assumes that the slice is sorted.
func binarySearch(s []int, qval int) int {
	length := len(s)
	low := 0
	high := length - 1

	count := 0
	for low <= high {
		count++
		// See Josh Bloch's blog post about this next line.
		// http://googleresearch.blogspot.com/2006/06/extra-extra-read-all-about-it-nearly.html
		// Guess the midpoint value between the current low and high markers.
		mid := low + (high-low)/2
		midVal := s[mid]
		//fmt.Printf("%v: %v %v %v\n", count, low, midVal, high)
		// Change this if you're impatient.
		time.Sleep(time.Second)
		vis(length, qval, low, mid, high)

		// Narrow the boundaries, depending on which half the qval is in.
		if qval > midVal {
			low = mid + 1
		} else if qval < midVal {
			high = mid - 1
		} else {
			return mid // found the qval
		}
	}
	return -(low + 1) // qval not found
}

// Main: Sets up the slice and gets the query value, then
// calls binarySearch().
func main() {
	// This is a slice:
	s := []int{
		0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
		17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32,
		33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48,
		49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64}

	// Sort it before binary search (just in case).
	sort.IntSlice.Sort(s)

	// Change qval to see different searches.
	qval := 21
	fmt.Printf("Searching for: %v\n", qval)

	result := binarySearch(s, qval)
	fmt.Printf("%v\n", result)
	if result < 0 {
		fmt.Printf("%v not found.\n", qval)
	}
}