Defer in D

Xinok via Digitalmars-d digitalmars-d at puremagic.com
Mon Mar 21 17:12:59 PDT 2016


On Monday, 21 March 2016 at 17:46:05 UTC, Dmitry Olshansky wrote:
> ...
> 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.

D and Go have different mechanisms for handling 
errors/exceptions. I'll refrain from debating "A is better than 
B" but I haven't seen any use case which isn't already adequately 
covered by the existing mechanisms in D.

However, one thing I do find inferior is the inability of D 
lambdas to capture by value. Thus, the simple example of 
"writeln(i)" may produce unexpected results.


@Nick: https://github.com/Xinok/scrapheap/blob/master/defer.d


More information about the Digitalmars-d mailing list