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

对指针使用延迟

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

对指针使用延迟

如果函数的目的是返回文件,为什么要在返回文件的函数中将其关闭?

在这种情况下, 调用者 有责任正确关闭文件,最好使用

defer

func usingGetConnection() {    f := getConnection("file.txt")    defer f.Close()    // Use f here}

尽管您的

getConnection()
函数吞没了错误,但是您应该使用多次返回值来指示类似以下问题:

func getConnection(fileName string) (*os.File, error) {    file, err := os.Open(fileName)    //Check for error    if err != nil {        return nil, err    }    return file, nil}

并使用它:

func usingGetConnection() {    f, err := getConnection("file.txt")    if err != nil {        panic(err) // Handle err somehow    }    defer f.Close()    // Use f here}


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

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

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