advantages:
- Runs fast
- Garbage collection
- Simpler objects
- efficient concurrency
- compiled language
OOP
- encapsulation : data + func
Go syntax
- structs (like class in java) , no inheritance/no constructors/no generics
- workspaces, three subdirectories (src, pkg and bin), workspace is defined by GOPATH env variable
- packages: group of related source files, can be imported by othr packages
package p1 package p2 import ( "p1", "p2" )
- main package, main() where the code execution starts
- import: access other packages; will search directories in GOROOT and GOPATH
- go build -> complies the program
- go doc -> prints documentation for a package
- go fmt -> formats source code files
- go get -> download packages and installs them
- go list -> lists all installed packages
- go run -> compiles .go files and runs the executable
- go test -> runs tests using files ending in “_test.go”
- variables -> must have a name and a type, declarations
var x,y int
- variable types : integer, floating point, strings,
Concurrency
- difficulties
when do tasks start/stop
what if one task needs data from another task
do tasks conflict in memory
Basics
- pointers
a pointer is an address to data in the memory
& operator returns the address of a variable/function - operator returns data at an address(dereferencing)
new() function creates a variable and returns a pointer to the variablevar x int = 1 var y int var ip *int ip = &x y = *ip ptr := new(int) *ptr = 3
-
variable scope
the places in code where a variable can be accessed
blocks {}
hierarchy of implicit blocks
universe block -> all go source
package block -> all source in package
file block -> all source in a file
if, for, switch -
deallocating space
when a variable is no longer needed, it should be deallocated, otherwise we will eventually run out of memory
stack(function calls, deallocate after func done) vs heap(persistent) - garbage collection(why it’s fast)
Hard to determine when a variable is no longer in usefunc foo() *int { x :=1 return &x } func main() { var y *int y = foo() fmt.Printf("%d", *y) }
Go is a complied language which enables garbage collection
Compiler determines stack vs heap
Garbage collection in the background -
comments, printing and integers
comments // or /* */
fmt.Printf(“Hi %s”, x)
integers - Type conversions
Most binary oeprations need operands of the same typevar x int32 =1 var y int16 =2 x = y x = int32(y)
- String packages
runes are divied into many different categories
provides a set of functions to test categories of runesIsDigit(r rune) IsSpace(r rune) IsLetter(r rune) ToUpper(r rune) Compare(a,b) Atoi(s)
Strings are immutable, but modified strings(new strings) are returned
- Constants
expression whose value is known at compile timeconst ( y = 4, x='abc')
Constants must be different but actual value is not important, each constant is assigned to a unique integer
Starts at 1 and incrementstype Grades int const ( A Grades = iota B C D F )
- Control flow
if else switch/case for i:=0; i<10;i ++ { fmt.Printf("hi ") } break and continue scan
Scan reads user input and takes a pointer as an argument, typed data is written to ponter, returns number of scanned items
fmt.Printf("Number of apples") num, err := fmt.Scan(&appleNum) fmt.Printf(appleNum)
- Composite datatypes
Arrays: Fixed-length series of elements of a chosen type
… for size in array literal infers size from number of initializersvar x [5]int x[0]=2 fmt.Printf(x[1]) var x [5]int = [5]{1,2,3,4,5} for i, v range x { fmt.Printf("ind %x value %y",i,v) }
Slices: A window on an underlying array
Variable size, up to whole array
Pointer, Length, Capacityarr := [...]string{"a","b","c"} sli1 := x[0:1]
Make: make() create a slice and array using make()
sli = make([]int, 10) sli = make([]int, 10, 15)
Append: Size of a slice can be increased by append()
HashTable: Contains key/value pairs
Tradeoffs:
advantages:
Faster lookup than list, constant time vs linear-time
Arbitrary keys: Not ints, like slices or arrays
disadvantages:
may have collisions
Maps: implementation of Hashtable
var idMap map[string]int
idMap = make(map[string]int))
idMap := map[string]int {"joe":123}
id, p := idMap["joe"] //id is value, p is presence of key
for key, val "= range idMap { fmt.Println(key, val)}
Struct: aggregate data type
Person Struct: Name, Address, phone
type struct Person {
name string
addr string
phone string
}
var p1 Person
p1.name = "joe"
x=p1.addr
p1 := new(Person)
p1 := Person(name:"Joe", addr: "a st.", phone: "123")
- Protocols and Formats
Requests for Comments (RFC): Definitions of Internet protocols and formats
Golang provides packages for important RFCs, Functions which encode and decode protocol formathttp.Get(wwww.google.com) net.Dial("tcp","google.com:80")
- JSON: atrribute-value format
All Unicode
Human-readable
Fairly compact representation
Types can be combined resursively(Array of struts, struct in struct)
JSON marshalling -> generating JSON representation from an object
JSON unmarshalling -> converts a JSON []byte into a Go object
- Files
Linear acces, not random access
Open, Read, Write, Close, Seek
```
dat, e := ioutil.ReadFile(“test.txt”) // dat is []byte filled with contents of entire file
dat = “Hello, world”
err := ioutil.WriteFile(“outfile.txt”, dat, 0777)
- os Package File Access
os.Open()
os.Close()
os.Read() // control the amount read
os.Write()
f, err := os.Open(“dt.txt”)
barr := make([]byte, 10)
nb, err := f.Read(barr)
f.Close()
f, err := os.Create(“outfile.txt”)
barr := []byte{1,2,3}
nb, err := f.Write(barr)
nb, err := f.WriteString(“Hi”)
```