Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

go build

Install it

go install





Commands

CommandDescription
go run <src.go>Run some code
go buildCompile the code. Outputs to local folder. Executable has folder as name.
go installCompiles and places the output in workspace/bin
go env GOPATHOutputs the default workspace folder

Variables

Variables are defined using the following syntax:

var <variablename> <type>

example:

var x int

All variables have a zero value and are pre-initialized to their zero value. For example, an int would have a zero value of 0 and a string would have a zero value of empty string "".


Initializing the variable at declaration time:

var x int = 5

Quick Syntax: infers type based on value.

x:=5


Example:

Code Block
package main
  
import (
  "fmt"
)

func main(){
  var x int
  x = 5
  fmt.Println(x)
}


If Statements

Code Block
package main
  
import (
  "fmt"
)

func main(){
  var x int
  x = 5
  fmt.Println(x)
}

Loops

Arrays

Functions 

Example showing error return

Code Block
package main

import (
  "fmt"
  "error"
  "math"
)

func main() {
  result, err := sqrt(16)
  
  if err != nil {
    fmt.Println(err)
  } else {
    fmt.Println(result)
  }
}

func sqrt(x float64) (float64, error ) {
  if x < 0 {
    return 0, errors.New("Undefined for negative numbers")
  }
  return math.Sqrt(x), nil
} 


Structs/Types

Example of Person Type

Code Block
package main
  
import (
  "fmt"
)

type person struct {
  name string
  age int
}

func main(){
  p:= person{name: "Jake", age: 23 }
  fmt.Println(p)
}

Commands

...



  fmt.Println(p.age)
}


Pointers

Pass by Reference Example

Variables

Variables are defined using the following syntax:

var <variablename> <type>

example:

var x int

All variables have a zero value and are pre-initialized to their zero value. For example, an int would have a zero value of 0 and a string would have a zero value of empty string "".

Initializing the variable at declaration time:

var x int = 5

Quick Syntax: infers type based on value.

x:=5

Example:

Code Block
package main
  
import (
  "fmt"
)

func main(){
  vari x:= int7
  x = 5inc(&i)
  fmt.Println(i)
}

func inc(x *int) {
}

Structs

code
  *x++
}


References

...