Welcome to This Week in D! Each week, we'll summarize what's been going on in the D community and write brief advice columns to help you get the most out of the D Programming Language.
The D Programming Language is a general purpose programming language that offers modern convenience, modeling power, and native efficiency with a familiar C-style syntax.
This Week in D has an RSS feed.
This Week in D is edited by Adam D. Ruppe. Contact me with any questions, comments, or contributions.
See more at the announce forum.
This week's tip comes from p0nce's D idioms page and is on assuming @nogc.
One of the problems with using @nogc in practice is that a lot of functions that could be annotated with it aren't. (I have argued before that I feel this is a major design flaw in @nogc and I don't expect the situation to change much, but today we're talking about moving forward with the status quo regardless.) Unlike @safe which has @trusted to let you escape, @nogc has no middle ground.
But, you can hack it with some library magic:
import std.traits; // Casts @nogc out of a function or delegate type. auto assumeNoGC(T) (T t) if (isFunctionPointer!T || isDelegate!T) { enum attrs = functionAttributes!T | FunctionAttribute.nogc; return cast(SetFunctionAttributes!(T, functionLinkage!T, attrs)) t; } // This function can't be marked @nogc but you know with application knowledge it won't use the GC. void funcThatMightUseGC(int timeout) { if (unlikelyCondition(timeout)) throw new Exception("The world actually imploded."); doMoreStuff(); } void funcThatCantAffortGC() @nogc { // using a casted delegate literal to call non-@nogc code assumeNoGC( (int timeout) { funcThatMightUseGC(timeout); })(10000); }
If you do this, of course, you should inspect the source and/or use runtime profilers or debuggers to ensure it actually does what you want, but by using this brute-force cast solution, you can introduce the middle ground that the language neglected to open up more of the library ecosystem to your nogc code.
To learn more about D and what's happening in D: