Thread overview
Some strange behaviors of enums and string.startsWith
Apr 08, 2016
Andre
Apr 08, 2016
Adam D. Ruppe
Apr 08, 2016
Andre
April 08, 2016
Hi,

I have some issues with enums. Please have a look at the last 3 assertions.
It is annoying that I cannot directly use my StringEnum for startsWith.
Therefore I use std.conv.text to convert the string enum? to string.
But then the assertion fails, that is very strange, it fails only for string ":" but
not for string "b".

Is this a bug? => Tested with DMD 2.071 on windows.

Kind regards
André

enum ManifestConst = ":";
enum CharEnum {	a = ':' }
enum StringEnum{a = ":", b = "b"}

import std.string: startsWith, endsWith;
import std.conv: text;

void main()
{
	assert(	":abc".startsWith(CharEnum.a)); // OK
	assert(	":abc".startsWith(ManifestConst)); // OK
	//assert( "abc".startsWith(StringEnum.a)); // Compiler error
	assert( ":abc".startsWith(StringEnum.a.text)); // Assertion failure
	assert( "bc".startsWith(StringEnum.b.text)); // OK ???
}
April 08, 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.
April 08, 2016
On Friday, 8 April 2016 at 14:56:51 UTC, Adam D. Ruppe wrote:
> 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.

Thanks a lot, now the behavior makes sense.
I will create a feature request for the phobos issue.

Kind regards
André