Can't add a const ubyte to a dynamic array of ubyte?

Daniel Kozak kozzi11 at gmail.com
Tue Aug 20 09:49:21 UTC 2019


On Tue, Aug 20, 2019 at 11:30 AM ads via Digitalmars-d-learn
<digitalmars-d-learn at puremagic.com> wrote:
>
>
> How can I get around this? I want to ensure that the array is not
> mutated in the function in the signature too.
>

https://run.dlang.io/is/tehp3j

import std.stdio;

ubyte[] extend(in uint[] arr)
{
    ubyte[] result;
    foreach (n; arr)
    {
        if (n < 10)
        {
            result ~= cast(ubyte)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 ~= cast(ubyte)(digit - '0');
            }
        }
    }
    return result;
}

unittest
{
    import std.algorithm : equal;
    assert(extend([1, 25, 70, 0]).equal([1, 2, 5, 7, 0, 0]));
}


More information about the Digitalmars-d-learn mailing list