Skip to content

Latest commit

 

History

History
130 lines (93 loc) · 4.29 KB

go.md

File metadata and controls

130 lines (93 loc) · 4.29 KB

About

Imports

import "foo"
import "bar"

import (  // "Factored" import style is recommended
    "foo"
    "bar"
)
  • If you import ("package1" "package2") etc, you can use the symbol package1 in the namespace.
  • The foo in "package1/foo" refers to the module that begins with package foo. If you do that, foo will be in the namespace.
  • In Go, a name is exported if it begins with a capital letter.. This is why fmt.Println look stupid.

Comments

// comment

Data types

Common primitive types: bool (default false), string (default ""), int, uint, byte, float64, complex128 (default 0)

To convert a type to another, use type cast

var i int = 0
var foo float64 = float64(int)  // or foo := float64(int)
  • << shifts the bit. 1 << 10 is 1024.

Entry point

package main

func main() {
    // here
}
func something(x int, y int) int {  // Same as func something(x, y int) int
    // type comes after the variable name.
    return x + y
}

function two_arguments(foo int, bar int) (int, int) {  // Declare return types of each item
    return foo, bar
}
var foo, bar, baz bool  // type is last
var foo, bar = 0, false  // type -can- be omitted if values are given

foo, bar := two_arguments("hello", "world")  // Use `:=` to assign with the implied type

// you can also infer an infer
baz := bar

  • const instead of var
  • No := assignment; however, since constants can only be character, string, boolean, or numeric values, they will be inferred.
  • Convention seems to be CapitalizedVariableName.

Just typing return returns all of its declared variables at the point. Naked return statements should be avoided to improve readability.

func foo(bar int) (x, y int) {  // If a function says it returns x and y...
    x = 1
    y = 2
    return  // ... it returns x and y.
}

defer

defer something() runs after the rest of the function completes. You cannot have compound statements like defer something(); something_else() but you can have multiple defers, where the defers are run in reverse order (stack).

defer fmt.Println("world")
defer fmt.Println("poop")
fmt.Println("hello")

// Prints "hello poop world"

Flow control

Exceptions