Andy Truong
PHP Developer
[WIP]
Andy Truong
@thehongtt
December 2015
// @file anything.go — play.golang.org/p/t9pJKg1gml
package main
import "fmt"
func main() {
fmt.Println("Hello world!")
}
go run anything.goimport "fmt"
// Single line importing
import ("net/http", "net/url")
// Prefered way
import (
// Core packages
"encoding/json"
// Importing groups
atbar "github.com/andytruong/foo/bar"
)
// Classic function
func add(x int, y int) int {
return x + y
}
// Short params
func add(x, y int) int {
return x + y
}
// Short return
func add(x, y) (z int) {
z = x + y
return
}
// Return multiple values
func swap(x, y int) (int, int) {
return y, x
}
// Return multiple values + short return
func split(sum int) (x, y int) {
x = sum * 4 / 9
y = sum - x
return
}
// classic
const f = "%T(%v)\n"
// Multiple
const (
Big = 1 << 100
Small = Big >> 99
)// Not initialized value. Default is false
var c, python, java bool
// With init value
var i, j int = 1, 2
// Short syntax
age := 32
if true {
fmt.Println("True")
}
if true {
fmt.Println("True")
} else {
fmt.Println("False")
}
// If with short statement
// isTrue is only available inside if block
if isTrue := true; isTrue {
fmt.Println("True")
}
// No break
switch runtime.GOOS {
case "darwin":
fmt.Println("OS X.")
case "linux":
fmt.Println("Linux.")
default:
fmt.Printf("%s.", runtime.GOOS)
}
// No input
switch {
case true:
fmt.Println("True")
case false:
fmt.Println("False")
}
// Basic for
sum := 0
for i := 0; i < 10; i++ {
sum += 1
}
// For with only condition checking
sum := 1
for sum < 1000 {
sum += sum
}
// For without statement
sum := 1
for {
sum += sum
if sum > 1024 {
break
}
}
func main() {
defer fmt.Println("3")
defer fmt.Println("2")
fmt.Println("1")
}i := 42
f := float64(i)
u := uint(f)
type SuperString string
func main() {
s := SuperString("My string")
fmt.Println(s)
}
type person struct {
name string
year int
}
type Vertex struct {
x, y int
}
v1 := Vertex{1, 2} // {1 2}
v2 := Vertex{y: 2} // {0 2}
v3 := Vertex{} // {0 0}
// Define a pointer to a type
var p *int
// Short syntax
i := 1
p := &i
// Pointer access
*p += 1; fmt.Println(*p)
// Define
var a [2]string
// Write
a[0] = "Hello"
a[1] = "world!"
// Read
fmt.Println(a[0], a[1])
// Define
var a [2]string
// Write
a[0] = "Hello"
a[1] = "world!"
// Read
fmt.Println(a[0], a[1])
var s []int{1, 2, 3, 4, 5}
var ss [][]string{
[]string{"x", "_", "_"},
[]string{"_", "x", "_"},
[]string{"_", "_", "x"},
}
// Access
s[1:2]
s[:3]
s[3:]
// Look
for k, v := range s {
fmt.Println(k, v)
}
// Exercise: Print ss
By Andy Truong