Created
July 30, 2015 14:45
-
-
Save siennathesane/98b45085cbd96b2bb550 to your computer and use it in GitHub Desktop.
Go reference file.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package go_learn | |
import ( | |
fmt | |
io/ioutil | |
m "math" | |
net/http | |
strconv | |
) | |
func main() { | |
fmt.println("Hello world!") | |
beyondHello() | |
} | |
func beyondHello() { | |
var x int | |
x = 3 | |
y := 3 // := is equal to var x int or var y bool | |
sum, prod := learnMultiple(x, y) | |
fmt.println("sum: ", sum, "prod: ", prod) | |
learnTypes() | |
} | |
/* | |
multi-line comments | |
*/ | |
func learnMultiple(x, y, int) (sum, prod int) { | |
return x +y, x * y | |
} | |
func learnTypes() { | |
str := "Learn Go!" | |
s2 := `A "raw" string | |
can incude line breaks. | |
Interesting.` | |
g := '√' | |
f := 3.14159 | |
c := 3 + 4i | |
var u uint = 7 //can declare on the same line. | |
var pi float32 = 22. / 7 | |
n := byte('\n') | |
var a4 4[int] // known length array of 4 integers, all starting at 0. | |
a3 := [...]int{3, 1, 5} //unknown fixed length array with integers. | |
s3 := []int{4, 5, 9} // unknown length slice | |
s4 := make([]int, 4) // makes a 4 int length slice, each slice is initialised with 0, this is default | |
var d2 [][]float64 // only declare, nothing has been allocated. | |
bs := []byte("a byte slice") // type conversion, string > byte. | |
s =: []int{1, 2, 3} | |
s = append(s, 4, 5, 6) | |
fmt.println(s) | |
s = append(s, []int{7, 8, 9}...) | |
fmt.println(s) | |
/* | |
These are initialised as int types because learnMemory(p, q *int) forces their type. Interesting! | |
*/ | |
p, q := learnMemory() | |
fmt.println(*p, *q) // the * follows a pointer, which was set at `p, q := learnMemory() | |
m := map[string]int{"three": 3, "four", 4} //map[key-type]value-type{key:value} is just a key:value dictionary. | |
m["one"] = 1 // adding a new key:value | |
// the variable has to be used, this will allow a placeholder but discard it's value. now that's useful. | |
_, _, _, _, _, _, _, _, _, _ = str, s2, g, f, u, pi, n, a3, s4, bs | |
fmt.Println(s, c, a4, s3, d2, m) | |
learnFlowControl() | |
} | |
func learnNamedReturns(x, y int) (z int) { // so it's function(arg, kwarg type) (return type) useful! | |
z = x * y | |
return /* z is implicit, and is called a naked return. if there were more then one variable, all varibables would | |
be implicit. */ | |
} | |
func learnMemory() (p, q int) { // no args, just the return. | |
p = new(int) // allocates memory for an int, but nothing more. | |
s := make([]int, 20) // empty slice with 20 ints as a single block of memory. | |
s[3] = 7 //adding third value. | |
r := -2 | |
return &s[3], &r // "&" calls the address pointer. in thie case, it's returned as an int because of the return type | |
// declaration above. useful! | |
} | |
func expensiveComputation() float64 { //declaring the type that will be returned. | |
return m.Exp(10) | |
} | |
func learnFlowControl() { | |
if true { | |
// braces like in c++ | |
fmt.println("This is true!") | |
} | |
if false { | |
// something. | |
} else { | |
//something else. | |
} | |
x := 42.0 | |
switch x { //switch is the context for chained `if` statements. | |
case 0: | |
case 1: | |
case 42: | |
case 43: | |
default: //this is a default execution. | |
} | |
for x := 0; x <3; x++ { //c++ style looping. oh boy, haha. | |
fmt.println("iteration ", x) | |
} | |
for { //infinite loop. | |
break | |
continue //unreached | |
} | |
for key, value := range map[string]int{"one": 1, "two": 2, "three": 3} { | |
fmt.println("key=%s, value=%d\n", key, value) | |
} | |
for y := expensiveComputation(); y > x { | |
x = y | |
} | |
xBig := func() bool { | |
return x > 10000 // References x declared above switch statement. | |
} | |
fmt.println("xBig: ", xBig()) | |
x = 1.3e3 | |
fmt.println("xBig: ", xBig()) | |
fmt.println("Add + double numbers: ", | |
func(a, b int) int { | |
return (a + b) * 2 | |
}(10, 2)) | |
goto love | |
love: | |
learnFunctionFactory() | |
learnDefer() | |
learnInterfaces() | |
} | |
func learnFunctionFactory() { | |
fmt.println(sentenceFactory("summer")"A beautiful", "day!") | |
d := sentenceFactory("summer") | |
fmt.println(d("A beautiful", "day!")) | |
fmt.println(d("A lazy", "afternoon!")) | |
} | |
//the function decorating is a little ridiculous, but hey, whatever. | |
func sentenceFactory(mystring string) func(before, after string) string { | |
return func(before, after string) string { | |
return fmt.Sprintf("%s %s %s", before, mystring, after) | |
} | |
} | |
func learnDefer() (ok bool) { | |
defer fmt.println("deferred statements execute in LIFO order.") | |
defer fmt.println("\nThis line is being printed first because") | |
//this would be good for file handling to keep the open() and close() principles close by. | |
return true | |
} | |
// Stringer is now an interface type with the method String() | |
type Stringer interface { | |
String() string | |
} | |
// this is now a structure with x and y as ints. | |
type pair struct { | |
x, y int | |
} | |
func (p pair) String() string { | |
return fmt.Sprintf("(%d, %d)", p.x, p.y) | |
} | |
func learnInterface() { | |
p := pair{3, 4} | |
fmt.println(p.String()) | |
var i Stringer | |
i = p //this is valid because Stringer utilises String() as well | |
fmt.println(i.String()) | |
fmt.println(p) | |
fmt.println(i) | |
learnVariadicParams("great", "learning", "here!") | |
} | |
func learnVariadicParams(myStrings ..interface{}) { | |
for _, param := range myStrings { //the udnerscore ignores the index/key index requirements. | |
fmt.println("param: ", param) | |
} | |
learnErrorHandling() | |
} | |
func learnErrorHandling() { | |
m := map[int]string{3: "three", 4: "four"} | |
if x, ok := m[1]; !ok { | |
fmt.println("no one there.") | |
} else { | |
fmt.println(x) | |
} | |
if _, err := strconv.Atoi("non-int"); err != nil { | |
fmt.println(err) | |
} | |
learnConcurrency() | |
} | |
//channels are concurrency safe objects. | |
func inc(i int, c chan int) { | |
c <- i + 1 // send operator when a channel appears on the left. | |
} | |
func learnConcurrency() { | |
//make an empty slice | |
c:= make(chan int) | |
//creating new goroutines | |
go inc(0, c) | |
go inc(10, c) | |
go inc(-805, c) | |
fmt.println(<-c, <-c, <-c) // channel is on the right, therefore it's a receive operator. | |
cs := make(chan string) | |
ccs := make(chan chan string) | |
go func() {c <- 84} () //new function and goroutine | |
go func() {cs <- "wordy"} () | |
select { | |
// looks like `switch`, however it will pull from case statements once they are ready to communicate. | |
case i := <- c: | |
fmt.println ("it's a %T", i) | |
case <- cs: | |
fmt.println("it's a string!") | |
case <- ccs: | |
fmt.println("didn't happen.") | |
} | |
learnWebProgramming() | |
} | |
func learnWebProgramming() { | |
go func() { | |
err := http.ListenAndServer(":8080", pair{}) | |
fmt.println(err) //not ignoring errors here. | |
} () | |
requestServer() | |
} | |
func (p pair) ServeHTTP(w http.ResponseWriter, r *http.Request) { | |
w.Write("Learned Go principles!") | |
} | |
func requestServer() { | |
resp, err := http.Get("http://localhost:8080") | |
fmt.println(err) | |
defer resp.Body.Close() | |
body, err := ioutil.ReadAll(resp.Body) | |
fmt.println("\nWebserver said: `%s`", string(body)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment