Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add the feature for go-lang like Defer #46485

Closed
kylincaster opened this issue Aug 26, 2022 · 3 comments
Closed

Add the feature for go-lang like Defer #46485

kylincaster opened this issue Aug 26, 2022 · 3 comments

Comments

@kylincaster
Copy link

The Defer function refers to take some operation on the exit of the section or the function, which is very convinient for case with resouce need to be released afterwards.
For example in the function with the multiple exit like.

function connect(...)
f = open(file)

if condition
	close(f)
	return ...
else
	close(f)
	return xxx

if the defer feature is added, the code could be simplied as

function connect(...)
f = open(file)
@defer close(f)
if condition
	return ...
else
	return xxx

I suggest to implement @defer as

macro defer(f(x...))
	ccall(:jt_func_defer, f, x...)
end

where :jt_func_defer is some julia C-interface which invokes the expression f(x...) at the exit of function.

@gbaraldi
Copy link
Member

I believe there is https://github.com/adambrewster/Defer.jl which kinda does this.

@kylincaster
Copy link
Author

I believe there is https://github.com/adambrewster/Defer.jl which kinda does this.

Thank you I have a try on Defer, which works exactly as I expected.

@KristofferC
Copy link
Member

See also the long discussion in #7721.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants