Skip to content

Instantly share code, notes, and snippets.

@caingougou
Last active September 28, 2015 06:33
Show Gist options
  • Save caingougou/7afc10a89b710d1a37c1 to your computer and use it in GitHub Desktop.
Save caingougou/7afc10a89b710d1a37c1 to your computer and use it in GitHub Desktop.
Learn go
package main
import (
"fmt"
"net/http"
"strconv"
)
func main() {
fmt.Println("Hello world")
// calculate()
//
// types()
//
// flowcontrol()
//
// interfaces()
//
// error()
concurrency()
err := http.ListenAndServe(":8080", pair{})
fmt.Println(err)
}
func calculate() {
var x int
x = 3
y := 4
sum, prod := multiple(x, y)
fmt.Println("Numbers:", x, y)
fmt.Println("Sum", sum, "Prod", prod)
}
func multiple(x int, y int) (sum, prod int) {
return x + y, x * y
}
func types() {
s := "String"
s2 := `"Raw"
"Data"`
f := 3.14 // float64
c := 3 + 4i // complex128
var u uint = 7 // unsigned int
var pi float32 = 22. / 7 // float32
n := byte('\n') // byte = uint8
// array is fixed length
var a4 [4]int
a3 := [...]int{1, 2, 3} // inited
// slice is dynamic
s3 := []int{3, 4, 5} // inited
s4 := make([]int, 4) // also inited with all 0
var d2 [][]float64
bs := []byte("a slice") // cast type
m := map[string]int{"three": 3, "four": 4}
m["one"] = 1
fmt.Println(s, s2, f, c, u, pi, n, a4, a3, s3, s4, d2, bs, m)
}
func y() int {
return 1e6
}
func flowcontrol() {
if true {
fmt.Println("True")
}
if false {
} else {
}
x := 1
switch x {
case 0:
fmt.Println("Won't happen")
case 1:
fmt.Println("Sure")
case 2:
fmt.Println("Won't get here either")
}
for x := 0; x < 3; x++ {
fmt.Println("iteration ", x)
}
for {
break
continue
}
if y:= y(); y > x {
x = y
}
xBig := func () bool {
return x > 100
}
fmt.Println("xBig: ", xBig())
x /= 1e5
fmt.Println("xBig: ", xBig())
}
type Stringify interface {
String() string
}
type pair struct {
x, y int
}
func (p pair) String() string {
return fmt.Sprintf("(%d, %d)", p.x, p.y)
}
func (p pair) ServeHTTP(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Fucking cool!"))
}
func interfaces() {
p := pair{3, 4}
fmt.Println(p.String())
var i Stringify
i = p
fmt.Println(i.String())
fmt.Println(p)
fmt.Println(i)
}
func error() {
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("string"); err != nil {
fmt.Println(err)
}
}
func inc(i int, c chan int) {
c <- i + 1
}
func concurrency() {
c := make(chan int) // make a slice, init slice, map and channel
go inc(0, c) // go is a statement to start a new goroutine
go inc(10, c)
go inc(-805, c)
fmt.Println(<-c, <-c, <-c) // read from channel
cs := make(chan string)
cc := make(chan chan string)
go func() { c <- 84}()
go func() { cs <- "wordy"}()
select {
case i := <-c:
fmt.Println("it's a", i)
case s := <-cs:
fmt.Println("it's a string:", s)
case <-cc:
fmt.Println("nothing")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment