Dmitry Bubnenkov
Dmitry Bubnenkov

Reputation: 9869

What is the right way to convert Variant to proper type?

I use mysql-native that return Variant data type. I need to convert it to standard types like int, string etc.

D have std.conv, but std.variant also have methods for concretion.

I can't understand what difference between: get, coerce, toString and to (from std.conv).

Also it's sound very strange that convertsTo is return bool. By it's name I expected that it should do convention. IMHO isConvertable is more proper name for it.

Upvotes: 3

Views: 865

Answers (1)

mitch_
mitch_

Reputation: 1436

There are three ways to get the value from a Variant type:

  • Variant.peek!T: If the value currently being held by the Variant object is of type T, then a pointer to that value is returned. If it is holding a value of a different type, it returns null instead.

    Variant v = "42";
    string* ptr = v.peek!string;
    assert(ptr !is null && *ptr == "42");
    
  • Variant.get!T: If the value currently being held by the Variant object is of type T, return the value of it. Otherwise, a VariantException is thrown.

    Variant v = "42";
    assertThrown!VariantException(v.get!int);
    assertNotThrown!VariantException(v.get!string);
    
  • Variant.coerce!T: Returns the value currently held by the Variant object, explicitly convertedto type T. If the value cannot be converted to type T, then an Exception is thrown.

    Variant v = "42";
    string s = v.coerce!string;
    assert(s == "42");
    int i = v.coerce!int;
    assert(i == 42);
    

Upvotes: 4

Related Questions