Search code examples
dvariant

How to check if Variant not null before coerce it?


I an getting from database data with Variant type. I need to check if variable have any data before coerce it.

  cargpspoint.speed = point[0].coerce!int;

if point[0] will be null I will get exception. I need to do coerce only if variable have value. There is long way with:

if(point[0].hasValue && point[0].peek!(int) !is null)

Is there any way to do it shorter? Or at last to not throw Exception if there is null inside.

https://dlang.org/phobos/std_variant.html


Solution

  • You could check whether the typeid inside is void.

    import std.variant : Variant;
    
    struct CarGPSPoint
    {
        int speed;
    }
    
    void main()
    {
        Variant point[] = new Variant[5];
    
        CarGPSPoint cargpspoint;
    
        if ( point[0].type != typeid(void) )
            cargpspoint.speed = point[0].coerce!int;
    }
    

    Alternatively just catch and discard the exception.

    import std.variant : Variant, VariantException;
    
    struct CarGPSPoint
    {
        int speed;
    }
    
    void main()
    {
        Variant point[] = new Variant[5];
    
        CarGPSPoint cargpspoint;
    
        try
            cargpspoint.speed = point[0].coerce!int;
        catch (VariantException e) {}
    }