Can't add a const ubyte to a dynamic array of ubyte?
Jonathan M Davis
newsgroup.d at jmdavisprog.com
Tue Aug 20 10:20:29 UTC 2019
On Tuesday, August 20, 2019 3:27:36 AM MDT ads via Digitalmars-d-learn
wrote:
> import std.stdio;
>
> ubyte[] extend(in uint[] arr)
> {
> ubyte[] result;
> foreach (n; arr)
> {
> if (n < 10)
> {
> result ~= n;
> // source/app.d(10,11): Error: cannot
> append type const(uint) to type ubyte[]
> }
> else
> {
> import std.conv : to;
>
> foreach (digit; n.to!string)
> {
> result ~= digit.to!ubyte;
> }
> }
> }
> return result;
> }
>
> unittest
> {
> import std.algorithm : equal;
>
> assert(extend([1, 25, 70, 0]).equal([1, 2, 5, 7, 0, 0]));
> }
>
>
> How can I get around this? I want to ensure that the array is not
> mutated in the function in the signature too.
arr contains uints, not ubytes, so n is a uint, and you're trying to append
a uint to result, which is an array of ubytes. If you want to append n to
result, then you need to convert it to a ubyte - either by casting or by
using to!uint (the difference being that to will throw a ConvException if
the value of n doesn't fit in a ubyte). D does not allow implicit narrowing
conversions (because there's no guarantee that the value will fit in the
target type), so you can't assign a uint to a ubyte without an explicit
conversion - and that includes appending to an array of ubytes.
- Jonathan M Davis
More information about the Digitalmars-d-learn
mailing list