Go Reference, Cheatsheet

By pjain      Published July 29, 2019, 2:18 a.m. in blog Programming   

Basics

  • Comment // / /
  • No semi-colon necessary if newline - can add it!

Types, operators, strings

  • Integers +-int
  • Float 124.0 0.000123 Go has two floating point types: float32 and float64
  • complex64 and complex128
  • NaN, for things like 0/0)
  • Positive and negative infinity. (+∞ and −∞)

  • Operators

    • addition
    • subtraction
    • multiplication / division % remainder
  • Logical true false && and || or ! not

Vars - STATIC TYPED and constants

  • have a type
  • assigned a value
  • Names must start with a letter and may contain letters, numbers or the _ (underscore) symbol.
  • convention to use lower camel case like dogsName var x string x = "first " fmt.Println(x) x = x + "second" fmt.Println(x)

  • create and assign - type inferred x := "Hello World"

  • assign = x = 1 x = x+2 # x += 2 y = 3

  • equality == x == y # true

  • Note it is type violation for var changing type x := "first "; y := 2 # x = 2 # ERROR type changed .. x = "second"; y = 3 fmt.Println(x,y)

  • vars are mutable

  • Shorthand to define Multiple Variables = Use the keyword var (or const) followed by parentheses with each variable on its own line.

    var ( a = 5 b = 10 c = 15 )

  • constants = immutables

    const x string = "Hello World" x = "Some other string"

    Results in a compile-time error: .\main.go:7: cannot assign to x

  • var scope

  • At outer level - vars can be accessed insude functions ..

strings

Sequence of characters with a definite length used to represent text. Go strings are made up of individual bytes, usually one for each character. Use "

backticks allow multi-line strings

Escape char \n \t etc

"Hello World"
len("Hello")  #5
fmt.Println("Hello " + "World")  # concat
  • String index starts at 0, treated as objects "Hello World"[1] # e

  • Multibyte, Unicode Characters from other languages like Chinese are represented by more than one byte

control flow

  • for i := 1 for i <= 10 { fmt.Println(i) i = i + 1 }

    for i := 1; i <= 10; i++ { ... }

  • if if i % 2 == 0 { // even } else { //or else if // odd }

  • switch - can take any type - strings or numbers .. switch i { case 0: fmt.Println("Zero") case 1: fmt.Println("One") case 2: fmt.Println("Two") case 3: fmt.Println("Three") case 4: fmt.Println("Four") case 5: fmt.Println("Five") default: fmt.Println("Unknown Number") }

IO

  • Print() Println()

  • Scanf fmt.Print("Enter a number: ") var input float64 fmt.Scanf("%f", &input) output := input * 2 fmt.Println(output)

Go OOP

Go doesn't have classes but an intro at .. https://sites.google.com/site/gopatterns/object-oriented/classes


0 comments

There are no comments yet

Add new comment

Similar posts

Go Sample Full Apps

Go Quickstart

Go Setup Smarts

Go Concurrency 101