Skip to content

Instantly share code, notes, and snippets.

@eluleci
Last active August 29, 2015 14:07
Show Gist options
  • Save eluleci/f13ccb1ad3311218294c to your computer and use it in GitHub Desktop.
Save eluleci/f13ccb1ad3311218294c to your computer and use it in GitHub Desktop.
go quick guide

Go quick guide

types, structs arrays, maps

basic types

bool

string

int  int8  int16  int32  int64
uint uint8 uint16 uint32 uint64 uintptr

byte // alias for uint8

rune // alias for int32
	 // represents a Unicode code point

float32 float64

complex64 complex128

variables

var i int
var c, python, java bool

** variables with initializers **

var i, j int = 1, 2
var c, python, java = true, false, "no!"

** short variable decleration **

i := 1
c := true
java := "no!"

constants

const i = 23

type conversions

i := 42
f := float64(i)
u := uint(f)

structs

type Vertex struct {
    X int
	Y int
}

v := Vertex{1, 2}		// create with values
v := new(Vertex)		// allocates zeroed values

v.X = 23				// access field

pointers

p := Vertex{1, 2}
q := &p
q.X = 1e9

struct literals

p = Vertex{1, 2}  // has type Vertex
q = &Vertex{1, 2} // has type *Vertex
r = Vertex{X: 1}  // Y:0 is implicit
s = Vertex{}      // X:0 and Y:0

arrays

var a [2]string
a[0] = "Hello"
a[1] = "World"

slices

a := make([]int, 5)					// allocates 0
p := []int{2, 3, 5, 7, 11, 13}

slicing slice

s := p[1:4]			// from 1 to 4, contains 1
s := p[:4]			// from 0 to 4
s := p[4:]			// from 4 to end

maps

m := make(map[string]Vertex)

m["Bell Labs"] = Vertex{
    40.68433, -74.39967,
}

m = map[string]Vertex{
    "Bell Labs": Vertex{
	    40.68433, -74.39967,
    },
	"Google": Vertex{
    	37.42202, -122.08408,
    },
}

m = map[string]Vertex{
	"Bell Labs": {40.68433, -74.39967},
	"Google":    {37.42202, -122.08408},
}

mutating maps

m[key] = elem

elem = m[key]

delete(m, key)

elem, ok = m[key]		// test a key is present

conditions, loops

if conditions

if x < 0 {
    // do something
}

if x := y * z; x < 0 {
    // do something
}
// x is not accessible from outside of if's scope

if x := y * z; x < 0 {
    // do something
} else {
	// do something different	
}

switch

switch i {
case 0:
    // do something
case 23:
    // do something
default:
    // do something when none of the above is caught
}

switch with no condition

// can be used as if-else
switch {
case i == 0:
    // do something
case i == 23:
    // do something
default:
    // do something when none of the above is caught
}

loops

for i := 0; i < 10; i++ {
    // do something
}

// skip pre and post
for ; i < 10; {
    // do something
}

// use as while loop
for i < 10 {
    i++
}

range

p := []int{2, 3, 5, 7, 11, 13}

for i, v := range p {
    // i is index
    // v is value
}

for _, v := range p {
    // index is ignored
    // v is value
}

for i := range p {
    // i is index
    // value is ignored
}

functions, methods

functions

func add(x int, y int) int {
	return x + y
}

func add(x, y int) int {
	return x + y
}

__ multiple results __

func swap(x, y string) (string, string) {
	return y, x
}

// usage
a, b := swap("hello", "world")

** named results **

func split(sum int) (x, y int) {
x = sum * 4 / 9
	y = sum - x
    return
}

function values

hypot := func(x, y float64) float64 {
    return math.Sqrt(x*x + y*y)
}

function closure

func fibonacci() func() int {
	x := 0
	y := 1
	return func() int {
		x,y = y,x+y
		return x
	}
}

func main() {
	f := fibonacci()
    for i := 0; i < 10; i++ {
    	fmt.Println(f())
	}
}

methods

type Vertex struct {
	X, Y float64
}

// adding Abs function to type Vertex 
func (v *Vertex) Abs() float64 {
	return math.Sqrt(v.X*v.X + v.Y*v.Y)
}

func main() {
    v := &Vertex{3, 4}
	fmt.Println(v.Abs())
}

** You cannot define a method on a type from another package, or on a basic type.

interface

type Abser interface {
	Abs() float64
}

type Vertex struct {
	X, Y float64
}

func (v *Vertex) Abs() float64 {
	return math.Sqrt(v.X*v.X + v.Y*v.Y)
}

func main() {
	var a Abser
	v := Vertex{3, 4}
	
	// works because *Vertex implements Abser
	a = &v 
	
	// doesn't work becuase Vertex doesn't implement
	a = v
}

** A type implements an interface by implementing the methods.

error

type error interface {
	Error() string
}

concurrency

go routines

with wait group

var waitGroup = sync.WaitGroup{}

func say(s string) {
    fmt.Println(s)
	waitGroup.Done()
}

func main() {
	waitGroup.Add(1)		
	go say("world")			// runs in thread

	say("hello")

	waitGroup.Wait()
}

with channels

func sum(a []int, c chan int) {
    sum := 0
	for _, v := range a {
    	sum += v
    }
	c <- sum // send sum to c
}

func main() {
	a := []int{7, 2, 8, -9, 4, 0}

    c := make(chan int)
	go sum(a[:len(a)/2], c)
    go sum(a[len(a)/2:], c)
    
	x, y := <-c, <-c // receive from c

    fmt.Println(x, y, x+y)
}

buffered channels

// initialize with buffer size
ch := make(chan int, 100)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment