Go例子和成语

没有太多的Go语言代码可用于学习该语言,而且我敢肯定,我并不是唯一一个尝试过该语言的人。因此,如果您发现有关该语言的一些有趣信息,请在此处发布示例。

我也在寻找

  • Go中惯用的方式来做事,

  • C / C ++思维风格“移植”到Go,

  • 有关语法的常见陷阱,

  • 真的很有趣。


慕容708150
浏览 275回答 3
3回答

慕的地10843

推迟陈述“ defer”语句调用一个函数,该函数的执行被推迟到周围函数返回的那一刻。DeferStmt =“ defer”表达式。表达式必须是函数或方法调用。每次执行“ defer”语句时,都会对函数调用的参数进行评估并重新保存,但不会调用该函数。延迟的函数调用将在周围函数返回之前立即以LIFO顺序执行,但是在对返回值(如果有)进行求值之后才执行。lock(l);defer unlock(l);&nbsp; // unlocking happens before surrounding function returns// prints 3 2 1 0 before surrounding function returnsfor i := 0; i <= 3; i++ {&nbsp; &nbsp; defer fmt.Print(i);}更新:defer现在也处理惯用方式panic在例外样方式:package mainimport "fmt"func main() {&nbsp; &nbsp; f()&nbsp; &nbsp; fmt.Println("Returned normally from f.")}func f() {&nbsp; &nbsp; defer func() {&nbsp; &nbsp; &nbsp; &nbsp; if r := recover(); r != nil {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fmt.Println("Recovered in f", r)&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }()&nbsp; &nbsp; fmt.Println("Calling g.")&nbsp; &nbsp; g(0)&nbsp; &nbsp; fmt.Println("Returned normally from g.")}func g(i int) {&nbsp; &nbsp; if i > 3 {&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println("Panicking!")&nbsp; &nbsp; &nbsp; &nbsp; panic(fmt.Sprintf("%v", i))&nbsp; &nbsp; }&nbsp; &nbsp; defer fmt.Println("Defer in g", i)&nbsp; &nbsp; fmt.Println("Printing in g", i)&nbsp; &nbsp; g(i+1)}

狐的传说

Go对象文件实际上包含明文标题:jurily@jurily ~/workspace/go/euler31 $ 6g euler31.gojurily@jurily ~/workspace/go/euler31 $ cat euler31.6amd64&nbsp; exports automatically generated from&nbsp; euler31.go in package "main"&nbsp; &nbsp; import$$&nbsp; // exports&nbsp; package main&nbsp; &nbsp; var main.coin [9]int&nbsp; &nbsp; func main.howmany (amount int, max int) (? int)&nbsp; &nbsp; func main.main ()&nbsp; &nbsp; var main.initdone· uint8&nbsp; &nbsp; func main.init ()$$&nbsp; // local types&nbsp; type main.dsigddd_1·1 struct { ? int }$$!<binary segment>

繁华开满天机

我看到几个人抱怨“ for-loop”,类似“为什么i = 0; i < len; i++在这个时代必须说?”。我不同意,我喜欢for结构。如果愿意,可以使用长版本,但是惯用的Go是var a = []int{1, 2, 3}for i, v := range a {&nbsp; &nbsp; fmt.Println(i, v)}该for .. range构造在所有元素上循环并提供两个值-索引i和值v。range 也适用于地图和频道。不过,如果您不喜欢for任何形式,则可以在以下几行中定义each,map等等:type IntArr []int// 'each' takes a function argument.// The function must accept two ints, the index and value,// and will be called on each element in turn.func (a IntArr) each(fn func(index, value int)) {&nbsp; &nbsp; for i, v := range a {&nbsp; &nbsp; &nbsp; &nbsp; fn(i, v)&nbsp; &nbsp; }}func main() {&nbsp; &nbsp; var a = IntArr([]int{2, 0, 0, 9}) // create int slice and cast to IntArr&nbsp; &nbsp; var fnPrint = func(i, v int) {&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println(i, ":", v)&nbsp; &nbsp; } // create a function&nbsp; &nbsp; a.each(fnPrint) // call on each element}印刷0 : 21 : 02 : 03 : 9我开始非常喜欢Go :)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go