栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

在Go中使用defer

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

在Go中使用defer

我们通常

defer
用来关闭或释放资源。

周围的函数会在返回之前执行所有延迟的函数调用,即使它会慌乱。如果仅将函数调用放在周围函数的末尾,则在发生紧急情况时将跳过该调用。

而且,延迟函数调用可以通过调用

recover
内置函数来处理紧急情况。这不能通过函数结尾处的普通函数调用来完成。

每个延迟的调用都放在堆栈中,并在周围函数结束时以相反的顺序执行。颠倒顺序有助于正确分配资源。

defer
必须调用该语句才能调用函数。

您可以将其视为实现

try-catch-finally
块的另一种方法。

结束像

try-finally

func main() {    f, err := os.Create("file")    if err != nil {        panic("cannot create file")    }    defer f.Close()    // no matter what happens here file will be closed    // for sake of simplicity I skip checking close result    fmt.Fprintf(f,"hello")}

结束和恐慌处理,例如

try-catch-finally

func main() {    defer func() {        msg := recover()        fmt.Println(msg)    }()    f, err := os.Create(".") // . is a current directory    if err != nil {        panic("cannot create file")    }    defer f.Close()    // no matter what happens here file will be closed    // for sake of simplicity I skip checking close result    fmt.Fprintf(f,"hello")}

与try-catch-finally相比,好处是没有块和变量作用域的嵌套。这简化了周围功能的结构。

就像finally块一样,如果延迟函数调用可以到达返回的数据,则它们也可以修改返回值。

func yes() (text string) {    defer func() {       text = "no"    }()    return "yes"}func main() {    fmt.Println(yes())}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/403809.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号