| module > package > functions
mkdir project_dir
mkdir package_name
(This will be the name of final executable)go mod init project_dir/package_name
Go has 3 things (from OOP perspective):
Everything in Go has a type, every type has an interface.
Go doesn’t have these:
Case-sensitive syntax; If first letter of symbol is Uppercase, then it is publicly available (exported)
Builtin functions: golang.org/pkg/builtin
Types:
bool
string
[u]int(8 | 16 | 32 | 64)
float(32 | 64)
complex(64 | 128)
[u]int
= [u]int(32 | 64)
byte
uintptr
rune
%T
to find type of something""
and characters (int32 | byte) in single ''
like JavaVariables:
var <name> <type>
; Example: var someString string
<name> = <value>
; Example: someString = "this is a string"
<name> := <value>
; Example: anotherStr = "this is another string"
Constants:
const <name> <type> = <value>
new()
vs make()
new
is used to return a pointer of a “type” to an uninitialized memory locationmake
is used specifically with slices, maps and chans to allocate and initialize memory; it returns the object (as opposed to the pointer)Pointers:
var ptr *int
ptr := &val
&val
== ptr
val
== *ptr
Arrays:
var <name> = [<capacity>]<type>
, Example: var rgb = [3]string
rgb := [3]string{"red", "green", "blue"}
Slices:
<capacity>
in square brackets<name> := make([]<type>, <init_size>, [<capacity>])
capacity
is added, slice behaves like an arrayappend(<slice>, <value>)
- Add <value>
to <slice>
append(<slice>[<from>:<to>])
- Splice the slicesort.<type>(<slice>)
- Sort sliceMaps:
<name> := make(map[<key_type>]<value_type>)
(Here, []
does not mean optional, is part of the definition)countryCodes := make(map[string]string)
countryCodes["CA"] = "Canada"
delete(<map_name>, <key>)
- deletes key
from map_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>
}
fallthrough
explicitly at the end of case statementsFor 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"
+
-
*
/
%
&
|
^
&^
<<
>>
Date/Time:
import "time"
time.Now()
time.Date(...)