Some strange behaviors of enums and string.startsWith

Adam D. Ruppe via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Apr 8 07:56:51 PDT 2016


On Friday, 8 April 2016 at 14:38:10 UTC, Andre wrote:
> Therefore I use std.conv.text to convert the string enum? to 
> string.

That converts the *name* of the enum to string, not the contents. 
(BTW, I think the name of the enum is actually the more useful 
behavior.)

Use cast(string) if you want to get the content out.


> 	assert(	":abc".startsWith(CharEnum.a)); // OK
> 	assert(	":abc".startsWith(ManifestConst)); // OK

makes sense

> 	//assert( "abc".startsWith(StringEnum.a)); // Compiler error

I feel like that should work... Phobos is just being too picky on 
its types.

If you do cast(string) StringEnum.a, it is all good though.

> 	assert( ":abc".startsWith(StringEnum.a.text)); // Assertion

StringEnum.a.text == "a" because .text (and to!string) returns 
the NAME of the enum, not its value. So ":" != "a" and it fails.

> 	assert( "bc".startsWith(StringEnum.b.text)); // OK ???
> }

StringEnum.b.text == "b" because the name coincidentally matches 
the value so it passes.


More information about the Digitalmars-d-learn mailing list