首页 > 解决方案 > Ada - 可空类型

问题描述

如何将自定义类型初始化为 null ?

我想做这个 :

TestVar : T_MyType := null;

和 :

type T_MyType is
record
    field1 : float
    field2 : Boolean
end record

但我有一个错误:

在 myfile.ads 中定义的预期类型“T_MyType”

标签: typesnullada

解决方案


您可以使用变体记录模拟可为空的类型:

    type T_MyType(Is_Null : Boolean := True) is 
       record
          case Is_Null is
             when False => 
                field1 : Float
                field2 : Boolean
             when True =>
                null; -- no parameters
          end case;
       end record

       -- Example "Null" value.  Trying to use field1 or field2 will
       -- result in an exception as they are not available when Is_Null
       -- is set to True
       Null_MyType : constant T_MyType := (Is_Null => True);

此类型默认没有参数(Is_Null 默认为 True)。对于大型类型,您可能必须小心返回其中之一,因为它可能很昂贵(您需要查看您的编译器供应商以了解它是否对此进行了优化)。


推荐阅读