create fixed length string of characters

Jonathan M Davis newsgroup.d at jmdavisprog.com
Fri Aug 16 16:30:09 UTC 2024


On Friday, August 16, 2024 9:58:31 AM MDT Nick Treleaven via Digitalmars-d-
learn wrote:
> On Friday, 16 August 2024 at 13:30:53 UTC, IchorDev wrote:
> > On Friday, 16 August 2024 at 11:37:08 UTC, Nick Treleaven wrote:
> >> On Friday, 16 August 2024 at 06:15:18 UTC, Bruce wrote:
> >> ```d
> >> string s = a.dup; // copy to heap, assuming you need the data
> >> to escape (use a[] otherwise)
> >> s.writeln();
> >> ```
> >
> > I think you meant `idup`? `dup` will make it mutable.
>
> `dup` actually works. I tested the code before posting. It should
> be that `dup` is a template function which gets inferred as
> strongly `pure`, so the result is known to the compiler to be
> unique.
>
> https://dlang.org/spec/function.html#pure-factory-functions
>
> So perhaps `idup` is no longer needed.

Well, you if you use dup, you're asking for a mutable array, whereas if you
use idup, you're asking for an immutable array. Whether the result of dup is
then able to be implicitly converted to immutable based on whether the
operation is pure depends on the element type and where the result is used.
So, dup may very well work in this particular case, but in the general case,
you really want to be using idup if you want immutable. And in this
particular example, all it would take to make the result not immutable would
be to use auto instead of string.

- Jonathan M Davis





More information about the Digitalmars-d-learn mailing list