Defer in D

Dmitry Olshansky via Digitalmars-d digitalmars-d at puremagic.com
Mon Mar 21 10:46:05 PDT 2016


On 20-Mar-2016 02:16, Xinok wrote:
> I stumbled upon an example demonstrating defer in Go which I thought was
> interesting. Defer is similar to scope in D except they're called at end
> of function rather than end of scope; you can queue multiple defer calls
> by writing them inside of a loop. This implies that it internally builds
> a stack of delegates which are then executed LIFO once the function
> returns (or panics).
>
> https://tour.golang.org/flowcontrol/13
>

>
> I think a library solution is elegant enough that it doesn't need to be
> built into the language but that doesn't mean it needs to be in Phobos
> either. Does anybody have a use case for "defer" that isn't already
> adequately covered by scope statements?

The main use case in Go that needs it specifically as a function level 
primitive is  this:

files := []File{}
for i := paths {
	files[i], err := os.Open(paths[i])
	if err != nil {
		return errors.Errorf("Failed to open %s", paths[i])
	}
	defer files[i].Close()
}
... // lots of code using files


So in a nutshell - lack of RAII while operating on collections of resources.

-- 
Dmitry Olshansky


More information about the Digitalmars-d mailing list