digitalmars.D.learn - Some strange behaviors of enums and string.startsWith
- Andre (27/27) Apr 08 2016 Hi,
- Adam D. Ruppe (13/21) Apr 08 2016 That converts the *name* of the enum to string, not the contents.
- Andre (5/12) Apr 08 2016 Thanks a lot, now the behavior makes sense.
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 ??? }
Apr 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)); // OKmakes sense//assert( "abc".startsWith(StringEnum.a)); // Compiler errorI 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)); // AssertionStringEnum.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.
Apr 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:Thanks a lot, now the behavior makes sense. I will create a feature request for the phobos issue. Kind regards André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.
Apr 08 2016