Skip to content
wangb edited this page Nov 2, 2018 · 1 revision

hello world

package main

import "fmt"

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

variables

  • var a, b type = initial_a, initial_b
  • a := initial_a (no var, can only in function)
  • zero values // if value is not initialed the value will be zero value.
  • const a = 111

For loop

  • while: for i < n
  • c-style: for i := 0; i < n; i++ {
  • infinite-loop: for {
  • range iterate: for i/k, v := range array/map {

If/Else

  • no ternary: if i < 0 { a = 100 } else {a = 101}

Switch/Case

Array

  • golang array has length in it's type
  • var a [n]type
  • literal value: [n]type{a, b, c}

Slice

  • array without length
  • make([]type, init_size)
  • slice = append(slice, value)
  • slice operator: slice[low:]

Map

  • make(map[key-type]val-type)
  • n := map[string]int{"foo": 1, "bar": 2}

Function

  • func funcname (a type) returntype
  • multiple return type: func div (a double, b double) (int, error)
  • named return type

Pointer

  • pointer type: *type
  • dereference: *pointer_variable
  • variable to pointer: &variable

Struct

  • type sname struct {
  • struct method: fun (r receiver_type) (a int) return_type
    • values and pointers method are handled automatically in golang

Interface

  • type iface interface {
  • empty interface: interface {}
    • any value match empty interface

Error

Goroutine/Channel

  • start a goroutine: go fun()
  • make(chan string, buffer? int)
  • channel directions:
    • send: chan <- message
    • receive: message := <- chan
  • select: wait multiple channel
    • timeout
    • non-blocking
  • close channel
    • range over channel
Clone this wiki locally