Go
Notes
From “A tour of Go”
| module > package > functions
- Starting a go project:
- Make a project dir:
mkdir project_dir - Make a src dir:
mkdir package_name(This will be the name of final executable) - Initialize go modules:
go mod init project_dir/package_name
- Make a project dir:
From LinkedIn Learning “Learning Go” tutorial
-
Go has 3 things (from OOP perspective):
- Type - Definition of a thing
- Struct - Data of a thing
- Interface - Behavior of a thing
Everything in Go has a type, every type has an interface.
-
Go doesn’t have these:
- No (type) inheritance (Also, no classes/objects, duh)
- No overloading
- No “structured” exception handling (try/catch/finally)
- No implicit casting
-
Case-sensitive syntax; If first letter of symbol is Uppercase, then it is publicly available (exported)
-
Builtin functions: golang.org/pkg/builtin
-
Types:
- Everything has a type
- Some built-in data types:
boolstring[u]int(8 | 16 | 32 | 64)float(32 | 64)complex(64 | 128) - Some built-in data type aliases:
[u]int=[u]int(32 | 64)byteuintptrrune - Some built-in collection types: Arrays, Slices, Maps, Structs
- Some built-in language types: Functions, Interfaces, Channels, Pointers
- Use printf’s
%Tto find type of something - Note that strings are in double quotes
""and characters (int32 | byte) in single''like Java
-
Variables:
- Declaration:
var <name> <type>; Example:var someString string - Initialization:
<name> = <value>; Example:someString = "this is a string" - Shortcut:
<name> := <value>; Example:anotherStr = "this is another string"- Shortcut only works inside functions.
- Declaration:
-
Constants:
- Definition:
const <name> <type> = <value> - Cannot be reassigned
- Definition:
-
new()vsmake()newis used to return a pointer of a “type” to an uninitialized memory locationmakeis used specifically with slices, maps and chans to allocate and initialize memory; it returns the object (as opposed to the pointer)
-
Pointers:
- Declare a pointer:
var ptr *int - Declare & Initialize a pointer to val:
ptr := &val - Address of val :
&val==ptr - Value of val :
val==*ptr
- Declare a pointer:
-
Arrays:
- Syntax:
var <name> = [<capacity>]<type>, Example:var rgb = [3]string - Shorter syntax with Initialization:
rgb := [3]string{"red", "green", "blue"} - Arrays are not usually preferred, since they cannot be sorted or capacity-changed
- Syntax:
-
Slices:
- Slices used Arrays behind the scene, but are preferred over Arrays because their capacity can be changed at runtime
- The syntax for slices is same as arrays, except the omission of
<capacity>in square brackets - Another syntax:
<name> := make([]<type>, <init_size>, [<capacity>]) - If
capacityis added, slice behaves like an array - Slice functions:
append(<slice>, <value>)- Add<value>to<slice>append(<slice>[<from>:<to>])- Splice the slicesort.<type>(<slice>)- Sort slice
-
Maps:
- Like Object in JS, Dict in Python, Hash Table
- Syntax:
<name> := make(map[<key_type>]<value_type>)(Here,[]does not mean optional, is part of the definition) - Example:
countryCodes := make(map[string]string)countryCodes["CA"] = "Canada" - Map functions:
delete(<map_name>, <key>)- deleteskeyfrommap_name
-
Structs:
-
Like a Class in Java, Can encapsulate both data and methods (optional)
-
Example:
type dog struct { age int } d := dog{5} fmt.Printf("%+v\n", d) d.age += 1 fmt.Printf("%+v\n", d)
-
-
Channels:
-
If Statements:
// Syntax (no brackets around conditions) if <condition> {} else if <condition> {} else {} -
Switch Statements:
// Syntax switch <expression> { case <val>: <statements> ... default: <statement> }- case don’t fall through by default (they break if satisfied)
- must add
fallthroughexplicitly at the end of case statements
-
For Loops:
-
Syntax 1 (same old):
for i := 0; i < <some_int>; i++ { } -
Syntax 2 (for each):
for x, y := range <map | slice> { // x = key | index // y = value } -
Syntax 3 (while like):
for <condition> { // break and continue work as expected }
-
-
Functions:
func <name>(<args>) <return_type> {} -
I/O:
-
Console:
ip := bufio.NewReader(os.Stdin) fmt.Print("Enter something: ") name, _ := ip.ReadString('\n') fmt.Println("You entered: ", name) -
File:
-
-
Math:
import "math"- Go Math Package
- Arithmetic built-in:
+-*/% - Bitwise built-in:
&|^&^<<>>
-
Date/Time:
import "time"- Go Math Package
time.Now()time.Date(...)