//https://tour.golang.org package main
// 模块导入 import ( "fmt" "math" "runtime" "time" )
// redis 支持“发布/订阅”的消息模式,可以基于此构建聊天室等系统 // redis 贡献者之一,使用该模式开发的聊天室的例子,https://gist.github.com/348262
// 模拟求开方的函数1,限制循环的次数为10
func sqrt_simulate_1(x float64) float64 { z := 1.0 for i := 1; i < 10; i++{ z -= (z * z - x )/(2 * z) } return z }
// 优化的求开发,x不是很大的话,循环的次数会少
func sqrt_simulate_2(x float64) float64 { z := 1.0 delta := 0.000000001 for i := 1; math.Abs((z * z - x )/(2 * z)) > delta; i++{ z -= (z * z - x )/(2 * z) fmt.Println("---------call time:",i) } return z }
// switch 结构
func show_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.", os) }
}
// switch_evaluation_order
func switch_evaluation(){
fmt.Println("When is Saturday?") // 今天是星期几
today := time.Now().Weekday() // now_time := time.Now()
// now_hour := time.Now().Hour()
// now_min := time.Now().Minute()
// now_sec := time.Now().Second()
// fmt.Println(now_time, now_hour, now_min, now_sec)
switch time.Saturday {
case today + 0: fmt.Println("Today.")
case today + 1: fmt.Println("Tomorrow.")
case today + 2: fmt.Println("2 days later.")
default: fmt.Println("Too far away.")
}
}
// switch without a conditon ,可以用来做ie else else很长的那种逻辑
func switch_without_conditon(){ fmt.Println("Switch without a condtion") t := time.Now().Hour() switch { case t < 12: fmt.Println("Good morning.") case t < 17: fmt.Println("Good afternoon.") default: fmt.Println("Good evening.")
} }
// defer,上下文都返回后才执行 // defer都放进栈里,后进先出
func show_defer()
{
defer fmt.Println("Day")
defer fmt.Println("fucking")
fmt.Println("What") fmt.Println("a")
}
func counting(){
fmt.Println("Counting")
for i := 1; i < 10; i++
{ defer fmt.Println(i) }
fmt.Println("Done")
}
func main(){
fmt.Println(sqrt_simulate_1(2), math.Sqrt(2))
fmt.Println(sqrt_simulate_2(2), math.Sqrt(2))
fmt.Println(sqrt_simulate_2(70000), math.Sqrt(70000))
show_switch()
switch_evaluation()
switch_without_conditon()
show_defer() counting()
}
原文:http://www.cnblogs.com/Wolfanature/p/5831020.html