Casting random type to random struct - is this a bug?

Daniel Kozák via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed Jul 15 08:58:16 PDT 2015


On Wed, 15 Jul 2015 15:45:43 +0000
"rumbu" <rumbu at rumbu.ro> wrote:

> struct S { int a, b; }
> auto s = cast(S)10;
> //compiles and sets s.a to 10.
> 
> It works also for any other type, if the structure contains a 
> member of that type in the first position.
> 
> Is this normal behaviour?

Yes, this is OK

If you need to cast against diferent types you can try pointers:

import std.stdio;
struct S
{
	ubyte a;
	ubyte b;
}

void main() {
	ushort m = 65535;
	auto s = *(cast(S*)&m);
	writeln(s);
}


More information about the Digitalmars-d-learn mailing list