Go 杂谈

痞子汤 · · 671 次点击 · · 开始浏览    
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。

// 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

 


有疑问加站长微信联系(非本文作者)

本文来自:开源中国博客

感谢作者:痞子汤

查看原文:Go 杂谈

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

671 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传