std.file.read returns void[] why?
Steven Schveighoffer
schveiguy at yahoo.com
Thu Apr 17 05:59:20 PDT 2014
On Thu, 17 Apr 2014 07:57:35 -0400, Regan Heath <regan at netmail.co.nz>
wrote:
> On Wed, 16 Apr 2014 14:36:20 +0100, Spacen Jasset
> <spacenjasset at mailrazer.com> wrote:
>
>> Why does the read function return void[] and not byte[]
>>
>> void[] read(in char[] name, size_t upTo = size_t.max);
>
> One one hand the data is always /actually/ going to be a load of
> (u)bytes, but /conceptually/ it might be structs or something else and
> using void[] therefore doesn't /imply/ anything about what the data
> really is.
>
> I also thought that void[] was implicitly cast.. but it seems this
> either has never been the case or was changed at some point:
>
> import std.stdio;
>
> void main(string[] args)
> {
> byte[] barr = new byte[10];
> foreach(i, ref b; barr)
> b = cast(byte)('a' + i);
>
> void[] varr = barr;
> char[] carr;
>
> //carr = barr; // Error: cannot implicitly convert expression (barr) of
> type byte[] to char[]
> carr = cast(char[])barr;
>
> //carr = varr; // Error: cannot implicitly convert expression (varr) of
> type void[] to char[]
> carr = cast(char[])varr;
>
> writefln("%d,%s", carr.length, carr);
> }
>
> I am curious, was it ever possible, was it changed? why? It's always
> "safe" - as the compiler knows how much data the void[] contains, and
> void[] is "untyped" so it sorta makes sense to allow it..
It was never possible. You must explicitly cast to void[].
void[] makes actually little sense as the result of whole-file read that
allocates. byte[] is at least usable and more accurate. In fact, it's a
little dangerous to use void[], since you could assign pointer-containing
values to the void[] and it should be marked as NOSCAN (no pointers inside
file data).
However, when using the more conventional read(void[]) makes a LOT of
sense, since any T[] implicitly casts to void[].
-Steve
More information about the Digitalmars-d-learn
mailing list