Cannot cast char[] to string.

Jonathan M Davis jmdavisProg at gmx.com
Thu Nov 14 20:31:46 PST 2013


On Thursday, November 14, 2013 20:45:55 Brad Anderson wrote:
> On Thursday, 14 November 2013 at 19:41:13 UTC, Agustin wrote:
> > I'm trying to use http://dlang.org/phobos/std_net_curl.html and
> > when i compile the same example i get:
> > 
> > cannot implicitly convert expression
> > (get(cast(const(char)[])address, AutoProtocol())) of type
> > char[] to string
> > 
> > string address = "http://dlang.org";
> > string _data = get(address);
> 
> You have two options:
> 
> string address = "http://dlang.org";
> string _data = get(address).idup(); // create immutable copy
> 
> or
> 
> string address = "http://dlang.org";
> char[] _data = get(address); // store mutable reference

If you want a string rather than char[], it's probably better to use 
std.conv.to. In the case of char[], it'll just end up calling idup for you, 
but if you use to!string(arr) as the normal means for converting arrays of 
characters to string, then you don't have to worry about the constness of the 
array, and if it turns out that the array was in fact string (which is quite 
easy to have happen if you're dealing with generic code), then it'll avoid 
iduping the array and will simply return it.

> A string (which is just an alias of immutable(char)[]) can't be
> made from a char[] without an assertion that the data pointed to
> is, in fact, immutable. You can do that using assumeUnique
> (inexplicably found in std.exception).

AFAIK, there is no way to make such an assertion. assumeUnique simply casts to 
immutable (though it will set the array passed in to null if you pass it an 
lvalue). So, it's completely up to the programmer to guarantee that the array 
is indeed unique. The primary used case for it is if you have to construct an 
array which you need to be immutable, and you need it to be mutable while 
you're setting all of its elements, in which case, you use assumeUnique on the 
array after you've set all of its elements, and you make sure that you don't 
have any other references to the array when you do that. If that's not what 
you're doing, you probably shouldn't be using assumeUnique. Certainly, using 
it on the result of a function that returns char[] is almost certainly wrong, 
and could result in very weird behavior, because the compiler is free to 
optimize based on the fact that the array is immutable, and if there's a 
mutable reference to that array, then you've subverted the type system, and 
ruined the compilers guarantees.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list