Giter Club home page Giter Club logo

Comments (6)

gogohead avatar gogohead commented on July 27, 2024 4

并非defer在return后调用
return不是原子性操作,1先复制 2在调用ret指令,而defer就在 这 1 2之间,不相信的话 使用下具名函数试试:
func test()(x int) {
x = 10
defer func() {
x++
}()
return x
}

from golangcodingtime.

TYtrack avatar TYtrack commented on July 27, 2024

defer在return后调用

from golangcodingtime.

green961 avatar green961 commented on July 27, 2024

我们知道在 Python 中可以使用 defer 实现对资源的管理
是 with 吧

from golangcodingtime.

ShawnQiang1 avatar ShawnQiang1 commented on July 27, 2024

有点像python 中 finanly的用法

from golangcodingtime.

wuxinlei avatar wuxinlei commented on July 27, 2024

defer和return涉及到一个具名参数问题,先赋值返回值,然后defer,最后return

from golangcodingtime.

JavaDevelopor avatar JavaDevelopor commented on July 27, 2024

/**

  • Java 代码释放资源try-catch-finally
    */
    try(// get resouece of os or db and so on..){
    // do some operations
    }catch(Exception ex){
    ex.printStackTrace();
    } finally {
    // resource release method.
    }

// go 版本
func method( ) int{
// get resource of os or db..
writer = os.openFile(...)
// release resource
defer writer.close()

// other operations
var a int = xxx()
return a
}

from golangcodingtime.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.