types - Ada - 可空类型
问题描述
如何将自定义类型初始化为 null ?
我想做这个 :
TestVar : T_MyType := null;
和 :
type T_MyType is
record
field1 : float
field2 : Boolean
end record
但我有一个错误:
在 myfile.ads 中定义的预期类型“T_MyType”
解决方案
您可以使用变体记录模拟可为空的类型:
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)。对于大型类型,您可能必须小心返回其中之一,因为它可能很昂贵(您需要查看您的编译器供应商以了解它是否对此进行了优化)。
推荐阅读
- c# - c# 关于 iList 的困惑
- python - 如何遍历整数列表,并引用字典中的最大键(所有整数),使其小于当前值?
- python - 第二次调用后返回不同字典的函数
- google-bigquery - BigQuery:如何根据重复项构建新行
- google-sheets - 如何计算合并单元格的总差异
- javascript - 为什么这些类在删除类别后没有隐藏?
- python - 将 SECRET_KEY 添加到 Heroku
- mysql - LIKE和AS SELECT * FROM在mysql中复制表有什么区别?
- oracle - 执行此查询时缺少右括号
- mongodb - Lambda 未通过 privatelink 连接到 Mongodb