On Github purplecode / lightning-talk-golang
package main
import "fmt"
func main() {
fmt.Println("Hello, World")
}
type Circle struct {
radius float64
}
type ipv4addr uint32
func addFactory(valueToAdd int) func(int) {
return func(value int) {
fmt.Println("%d + %d = %d", value, valueToAdd, value + valueToAdd)
return value + valueToAdd
}
}
type geometry interface {
area() float64
}
type rect struct {
width, height float64
}
type circle struct {
radius float64
}
func (r rect) area() float64 {
return r.width * r.height
}
func (c circle) area() float64 {
return math.Pi * c.radius * c.radius
}func measure(g geometry) {
fmt.Println(g.area())
}
func main() {
r := rect{width: 3, height: 4}
c := circle{radius: 5}
measure(r)
measure(c)
}
type Person struct {
name string
age int
}
func (p Person ) hello() {
fmt.Printf("Hi, I am %s. I am %d.\n", p.name, p.age)
}
type PersonWithPhone struct {
Person
number int
}
func main() {
a := Person{name: "Alice", age: 12}
a.hello()
b := PersonWithPhone{Person{"Bob", 15}, 123456}
b.age += 10
b.hello()
}
func fibonacci(c, quit chan int) {
x, y := 0, 1
for {
select {
case c <- x:
x, y = y, x+y
case <-quit:
fmt.Println("quit")
return
}
}
}
func main() {
c := make(chan int)
quit := make(chan int)
go func() {
for i := 0; i < 10; i++ {
fmt.Println(<-c)
}
quit <- 0
}()
fibonacci(c, quit)
}
@source: https://tour.golang.org/concurrency/6func CopyFile(dstName, srcName string) (written int64, err error) {
src, err := os.Open(srcName)
if err != nil {
return
}
defer src.Close()
dst, err := os.Create(dstName)
if err != nil {
return
}
defer dst.Close()
return io.Copy(dst, src)
}
@source: https://blog.golang.org/defer-panic-and-recoverfunc a() {
i := 0
defer fmt.Println(i)
i++
return
} // 0
func b() {
for i := 0; i < 4; i++ {
defer fmt.Print(i)
}
} // "3210":
func c() (i int) {
defer func() {
i++
}()
return 1
} // 2
@source: https://blog.golang.org/defer-panic-and-recoverfunc main() {
f()
fmt.Println("Returned normally from f.")
}
func f() {
defer func() {
if r := recover(); r != nil {
fmt.Println("Recovered in f", r)
}
}()
fmt.Println("Calling g.")
g(0)
fmt.Println("Returned normally from g.")
}
func g(i int) {
if i > 3 {
fmt.Println("Panicking!")
panic(fmt.Sprintf("%v", i))
}
defer fmt.Println("Defer in g", i)
fmt.Println("Printing in g", i)
g(i + 1)
}
Calling g. Printing in g 0 Printing in g 1 Printing in g 2 Printing in g 3 Panicking! Defer in g 3 Defer in g 2 Defer in g 1 Defer in g 0 Recovered in f 4 Returned normally from f.
export GOPATH=$HOME/work
export PATH=$PATH:$GOPATH/bin
bin/
hello # command executable
pkg/
linux_amd64/
github.com/golang/example/
stringutil.a # package object
src/
github.com/golang/example/
.git/ # repository metadata
hello/
hello.go # command source
stringutil/
reverse.go # package source
reverse_test.go # test source
func TestTimeConsuming(t *testing.T) {
if testing.Short() {
t.Skip("skipping test in short mode.")
}
//
t.Fail()
//
t.Error("I'm in a bad mood.")
}