Temporary @trusted scope
Jonathan M Davis
newsgroup.d at jmdavisprog.com
Tue Dec 18 10:42:51 UTC 2018
On Tuesday, December 18, 2018 3:14:50 AM MST Per Nordlöw via Digitalmars-d-
learn wrote:
> What's the preferred way of creating a temporary @trusted scope
> without writing a separate function?
>
> Similar to Rust's
>
> unsafe { /* unsafe stuff here */ }
Unfortunately, D does not currently have a way to do that. Only functions
can be marked with @trusted. However, the typical approach to this problem
is to use a lambda, which is more or less syntactically the same except that
it has some extra parens. e.g.
() @trusted { doUnsafe(); }();
or
auto result = () @trusted { getUnsafe:() }();
So, it's less than ideal, but it gets us close, and unless the code is long
enough that maybe it should be in its own function, it's better than
declaring a nested function, let alone declaring an entirely separate
function at module scope.
- Jonathan M Davis
More information about the Digitalmars-d-learn
mailing list