How to obtain Variant underlying type?

Paul Backus snarwin at gmail.com
Sun Jul 10 19:14:34 UTC 2022


On Sunday, 10 July 2022 at 18:31:46 UTC, drug007 wrote:
> On 7/10/22 20:26, anonymouse wrote:
>> On Sunday, 10 July 2022 at 06:26:37 UTC, jfondren wrote:
>>> ```d
>>> import std.variant : Variant;
>>>
>>> size_t[] shape(Variant v) {
>>>     import std.variant : VariantException;
>>>
>>>     size_t[] s;
>>>     try {
>>>         while (true) {
>>>             Variant elem = v[0];
>>>             s ~= v.length;
>>>             v = elem;
>>>         }
>>>     } catch (VariantException e) {
>>>         return s;
>>>     }
>>> }
>>> ```
>> 
>> Thank you very much.
>> 
>
> I'd like to say that using of exception to break loop is really 
> bad. Exception is exceptional thing but in the case above the 
> exception is ordinary completion of the loop happens on regular 
> basis. Don't do that.

For reference, this is the more correct way:

```d
while (cast(TypeInfo_Array) v.type !is null) {
     Variant elem = v[0];
     // etc.
}
```

Hard to blame anyone for not coming up with that on their first 
try, especially since `TypeInfo_Array` is not even 
documented--you have to read the source of `object.d` to find out 
about it.


More information about the Digitalmars-d-learn mailing list