admin管理员组文章数量:1026989
The @intCast()
causes undefined behavior when the target type cannot hold the resulting value. Is there something like @safeIntCast()
or a similar function which would return CastError!anytype
?
The @intCast()
causes undefined behavior when the target type cannot hold the resulting value. Is there something like @safeIntCast()
or a similar function which would return CastError!anytype
?
1 Answer
Reset to default 2std.math
has a number of functions for safe casting:
pub fn cast(comptime T: type, x: anytype) ?T
Cast an integer to a different integer type. If the value doesn't fit, return null.
pub fn lossyCast(comptime T: type, value: anytype) T
Cast a value to a different type. If the value doesn't fit in, or can't be perfectly represented by, the new type, it will be converted to the closest possible representation.
pub fn negateCast(x: anytype) !std.meta.Int(.signed, @bitSizeOf(@TypeOf(x)))
Returns the negation of the integer parameter. Result is a signed integer.
The @intCast()
causes undefined behavior when the target type cannot hold the resulting value. Is there something like @safeIntCast()
or a similar function which would return CastError!anytype
?
The @intCast()
causes undefined behavior when the target type cannot hold the resulting value. Is there something like @safeIntCast()
or a similar function which would return CastError!anytype
?
1 Answer
Reset to default 2std.math
has a number of functions for safe casting:
pub fn cast(comptime T: type, x: anytype) ?T
Cast an integer to a different integer type. If the value doesn't fit, return null.
pub fn lossyCast(comptime T: type, value: anytype) T
Cast a value to a different type. If the value doesn't fit in, or can't be perfectly represented by, the new type, it will be converted to the closest possible representation.
pub fn negateCast(x: anytype) !std.meta.Int(.signed, @bitSizeOf(@TypeOf(x)))
Returns the negation of the integer parameter. Result is a signed integer.
本文标签: castingHow to safely cast integer in zigStack Overflow
版权声明:本文标题:casting - How to safely cast integer in zig - Stack Overflow 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://it.en369.cn/questions/1745632336a2160238.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论