Function and flow control

flow control

if:

if x>10{    fmt.Println("x is greater than 10")}else{    fmt.Println("x is less than 10")}

The condition judegement allow one variable's declaration which only function in this logic judgement part

if x:= computedValue(); x>10{    fmt.Println("x is greater than 10")}else if x<3{    fmt.Println("x is less than 3")}else{    fmt.Println("x is greater than 3 and less than 10")}fmt.Println(x) //Here will raise some mistakes since x is not available here

For:

package mainimport "fmt"func main(){    sum := 0    for index := 0;index < 10;index++{        sum += index    }    fmt.Println("sum is equal to", sum)}

expression1 and expression2 could be omitted:

sum := 1for ;sum<1000;{    sum += sum}

break will shut down the loop, continue will break out this loop

for index := 10;index>0; index--{    if index == 5{        break //continue    }    fmt.Println(index)}//break: 10 9 8 7 6//continue: 10 9 8 7 6 4 3 2 1

for can coordinate with range for slice and map :

for key,value := range mapName{    fmt.Println("map's key is:",key)}

You can drop the unuesd values by introducing _:

for _,v := range mapName{    fmt.Println("map's value is:", v)}

Switch

switch interger{    case 4:        fmt.Println("The integer was <= 4")        fallthrough    case 5:        fmt.Println("The integer was <= 5")        fallthrough    case 6:        fmt.Println("The integer was <= 6")        fallthrough    default:        fmt.Println("default case")}

All case defautly possess the break, if we use fallthrough, then when the first matched case was found, the following cases will still be judged.

Function

func funcName(input1 type1, input2 type2, input3 type3)(output1 type1, output2 type2){    return value1, value2}
  • output1 output2 could be omitted,
package mainimport "fmt"func SumAndProduct(A int, B int)(int, int){    return A+B, A*B}func main(){    x := 3    y := 4    xPLUSy, xTIMESy := SumAndProduct(x,y)}

Changing parameters

func myfunc(arg ...int){}

arg is a slice accepting undetermined parameters whose type is int

Pointer

When we deliverying parameters from one function to another, we delivery the copy rather than the quotation, so we cannot change the value of the parameters by calling a function, if we intend to do so, pass the pointer.

package mainimport "fmt"//简单的一个函数,实现了参数+1的操作func add1(a *int) int { // 请注意,    *a = *a+1 // 修改了a的值    return *a // 返回新值}func main() {    x := 3    fmt.Println("x = ", x)  // 应该输出 "x = 3"    x1 := add1(&x)  // 调用 add1(&x) 传x的地址    fmt.Println("x+1 = ", x1) // 应该输出 "x+1 = 4"    fmt.Println("x = ", x)    // 应该输出 "x = 4"}

Here we pass the *int a, so the returned *a can change the x to x1.

The advantages of passing the pointer:

  • multiple functions can manipulate one object.

  • passing pointers is efficient and space-saving(8 bytes), when you would pass the struct or a big object, passing the pointer is a great method.

  • channel,slice,map 's realizing mechanisms are like pointers

defer

defer realize the stack, in functions, defer will be called before return.

func ReadWrite() bool {    file.Open("file")    defer file.Close()    if failureX {        return false    }    if failureY {        return false    }    return true}

Here is another usage, print the output reversely:

for i := 0; i < 5; i++ {    defer fmt.Printf("%d ", i)}

Define function as the value or type

Pass this function as the value:

package mainimport "fmt"type testInt func(int) bool // 声明了一个函数类型func isOdd(integer int) bool {    if integer%2 == 0 {        return false    }    return true}func isEven(integer int) bool {    if integer%2 == 0 {        return true    }    return false}// 声明的函数类型在这个地方当做了一个参数func filter(slice []int, f testInt) []int {    var result []int    for _, value := range slice {        if f(value) {            result = append(result, value)        }    }    return result}func main(){    slice := []int {1, 2, 3, 4, 5, 7}    fmt.Println("slice = ", slice)    odd := filter(slice, isOdd)    // 函数当做值来传递了    fmt.Println("Odd elements of slice are: ", odd)    even := filter(slice, isEven)  // 函数当做值来传递了    fmt.Println("Even elements of slice are: ", even)}

Taking f's place to be testInt()

Panic and recover:

Go cannot thrown exceptions as Java or C++, that is why panic and recover exist. But use them cautiously.

var user = os.Getenv("USER")func init(){    if user == ""{        panic("no value for $USER")    }}

This defer function can judge whether there is a panic function when executing the function

func throwsPanic(f func())(b bool){    defer func(){        if x:=recover();x!=nil{            b = true        }    }()    f()    return}
  • Conming accross the panic function, the function will immediately break off and jump to return, however the defer function will still be executed, so, if we put the recover function into the defer, we can detect whether we come accross the panic and take some measures.

main** and **init

These two reserved functions are forbidden to possess any input or output.main is the entry of the package main, init is the entry of all packages.

[图片上传失败...(image-154a5-1540311933507)]

import

When we inport something, the function load packages from the path abtained from environment variable GOROOT.

We can also import our own packages by absolute paths:

import "shorturl/model" //load $GOPATH/shorturl/model

Other methods to import packages:

import {    . "fmt"}

or

import {    f "fmt"}

then we can call functions of "fmt" by :

import {    Println("hello world")    //the first one    f.Println("hello world")    //the second one}
import {    _ "github.com/ziutek/mysql/godrv"}

No function will be included, but the init() will still be executed

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 211,561评论 6 492
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,218评论 3 385
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 157,162评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,470评论 1 283
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,550评论 6 385
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,806评论 1 290
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,951评论 3 407
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,712评论 0 266
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,166评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,510评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,643评论 1 340
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,306评论 4 330
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,930评论 3 313
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,745评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,983评论 1 266
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,351评论 2 360
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,509评论 2 348

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,309评论 0 10
  • 从开始工作到现在也近一年的时间了,在这一年的时间也做了几个关于智能电视的项目。从开始做智能电视开始自己去搜索资料发...
    sunwee阅读 2,794评论 8 18
  • 作者:忆江南 来自:《语文老师没教过的三国》 提起三国名将,各位应该会想到蜀国的关羽、张飞、赵云、马超、黄忠、魏延...
    松果老姨阅读 410评论 0 0
  • 昨天在孩子的要求下给他配上了家里的钥匙。 戴上了属于自己的钥匙,孩子显得格外开心,高兴的说:“太好了!我觉得自己是...
    蓝枫zdd阅读 90评论 0 0
  • 今天想和大家分享一部新的电影《羞羞的铁拳》,它出自开心麻花。有些人想必看过,或者听过,也许没听过,这都是小...
    旧渡头阅读 503评论 4 8