// h.go
package main
import (
"fmt"
"runtime"
)
func adder() func(int) int {
sum := 0
return func(x int) int {
sum += x
return sum
}
}
type Person struct {
Name string
Age uint8
}
/*
func (P Person) String() string {
return fmt.Sprintf("%v (%v years)", P.Name, P.Age)
}
*/
func (P *Person) String() string {
return fmt.Sprintf("%v (%v years)", P.Name, P.Age)
}
func main() {
for skip := 0; ; skip++ {
pc, file, line, ok := runtime.Caller(skip)
if !ok {
break
}
fmt.Printf("skip = %v, pc = %v, file = %v, line = %v\n", skip, pc, file, line)
}
//switch
fmt.Print("Go runs on ")
switch os := runtime.GOOS; os {
case "darwin":
fmt.Println("OS X.")
case "linux":
fmt.Println("Linux.")
default:
fmt.Printf("%s.\n", os)
}
//defer
fmt.Println("counting ")
for i := 0; i < 10; i++ {
defer fmt.Println(i * 10)
}
fmt.Println("done")
//指针
var i, j int = 42, 27
p := &i
fmt.Println("*p= ", *p)
*p = 21
fmt.Println("i = ", i)
p = &j
*p = *p / 3
fmt.Println("j = ", j)
//闭包
pos, neg := adder(), adder()
for i := 0; i < 10; i++ {
fmt.Println("pos = ", pos(i), "neg = ", neg(-i))
}
//interface
tom := &Person{"Tom", 22} //Person{"Tom", 22}
cat := &Person{"cat", 33} //Person{"cat", 33}
fmt.Println(tom, cat)
}
输出结果:
skip = 0, pc = 4763241, file = C:/Go/mycode/20170508/1/h.go, line = 34
skip = 1, pc = 4366150, file = C:/Go/src/runtime/proc.go, line = 185
skip = 2, pc = 4513537, file = C:/Go/src/runtime/asm_amd64.s, line = 2197
Go runs on windows.
counting
done
*p= 42
i = 21
j = 9
pos = 0 neg = 0
pos = 1 neg = -1
pos = 3 neg = -3
pos = 6 neg = -6
pos = 10 neg = -10
pos = 15 neg = -15
pos = 21 neg = -21
pos = 28 neg = -28
pos = 36 neg = -36
pos = 45 neg = -45
Tom (22 years) cat (33 years)
90
80
70
60
50
40
30
20
10
0
有疑问加站长微信联系(非本文作者)