跳转到内容
语言参考Zig 0.17.1官方原文

类型转换将一个类型的值转换为另一个类型。对于确定完全安全且无歧义的转换,Zig 提供类型强制转换;对于不应意外发生的转换,提供显式类型转换。此外还有第三种转换称为同级类型解析,用于根据多个操作数类型确定结果类型。

类型强制转换

预期一种类型、实际提供另一种类型时,会发生类型强制转换:

test_type_coercion.zig
test "type coercion - variable declaration" {
const a: u8 = 1;
const b: u16 = a;
_ = b;
}
test "type coercion - function call" {
const a: u8 = 1;
foo(a);
}
fn foo(b: u16) void {
_ = b;
}
test "type coercion - @as builtin" {
const a: u8 = 1;
const b = @as(u16, a);
_ = b;
}
命令行
$ zig test test_type_coercion.zig
1/3 test_type_coercion.test.type coercion - variable declaration...OK
2/3 test_type_coercion.test.type coercion - function call...OK
3/3 test_type_coercion.test.type coercion - @as builtin...OK
All 3 tests passed.

只有转换方式完全无歧义且保证安全时,才允许类型强制转换。唯一例外是 C 指针。

类型强制转换:更严格的限定

运行时表示相同的值可以通过转换收紧限定条件,无论这些限定条件嵌套多少层:

  • const —— 允许从非 const 转为 const
  • volatile —— 允许从非 volatile 转为 volatile
  • align —— 允许将较大的对齐值转为较小的对齐值
  • 允许将错误集合转换为其超集

这些转换在运行时不执行任何操作,因为值的表示未改变。

test_no_op_casts.zig
test "type coercion - const qualification" {
var a: i32 = 1;
const b: *i32 = &a;
foo(b);
}
fn foo(_: *const i32) void {}
命令行
$ zig test test_no_op_casts.zig
1/1 test_no_op_casts.test.type coercion - const qualification...OK
All 1 tests passed.

此外,指针可以强制转换为常量可选指针:

test_pointer_coerce_const_optional.zig
const std = @import("std");
const expectEqualStrings = std.testing.expectEqualStrings;
const mem = std.mem;
test "cast *[1][*:0]const u8 to []const ?[*:0]const u8" {
const window_name = [1][*:0]const u8{"window name"};
const x: []const ?[*:0]const u8 = &window_name;
try expectEqualStrings("window name", mem.span(x[0].?));
}
命令行
$ zig test test_pointer_coerce_const_optional.zig
1/1 test_pointer_coerce_const_optional.test.cast *[1][*:0]const u8 to []const ?[*:0]const u8...OK
All 1 tests passed.

类型强制转换:整数和浮点数扩宽

整数可以强制转换为能够表示原类型全部值的整数类型;同样,浮点数可以转换为能够表示原类型全部值的浮点类型。

test_integer_widening.zig
const std = @import("std");
const builtin = @import("builtin");
const expectEqual = std.testing.expectEqual;
const mem = std.mem;
test "integer widening" {
const a: u8 = 250;
const b: u16 = a;
const c: u32 = b;
const d: u64 = c;
const e: u64 = d;
const f: u128 = e;
try expectEqual(f, a);
}
test "implicit unsigned integer to signed integer" {
const a: u8 = 250;
const b: i16 = a;
try expectEqual(250, b);
}
test "float widening" {
const a: f16 = 12.34;
const b: f32 = a;
const c: f64 = b;
const d: f128 = c;
try expectEqual(d, a);
}
命令行
$ zig test test_integer_widening.zig
1/3 test_integer_widening.test.integer widening...OK
2/3 test_integer_widening.test.implicit unsigned integer to signed integer...OK
3/3 test_integer_widening.test.float widening...OK
All 3 tests passed.

类型强制转换:整数转浮点数

如果每个可能的整数值都能无需舍入地存入浮点类型(即整数精度不超过浮点数的有效位精度),整数可以强制转换为浮点数。无法安全强制转换的更大整数类型,必须使用 @floatFromInt 显式转换。

浮点类型 最大的整数类型
f16 i12 和 u11
f32 i25 和 u24
f64 i54 和 u53
f80 i65 和 u64
f128 i114 和 u113
c_longdouble 因目标平台而异
test_int_to_float_coercion.zig
const std = @import("std");
const expectEqual = std.testing.expectEqual;
test "implicit integer to float" {
var int: u8 = 123;
_ = ∫
const float: f32 = int;
const int_from_float: u8 = @intFromFloat(float);
try expectEqual(int, int_from_float);
}
命令行
$ zig test test_int_to_float_coercion.zig
1/1 test_int_to_float_coercion.test.implicit integer to float...OK
All 1 tests passed.
test_failed_int_to_float_coercion.zig
test "integer type is too large for implicit cast to float" {
var int: u25 = 123;
_ = ∫
const float: f32 = int;
_ = float;
}
命令行
$ zig test test_failed_int_to_float_coercion.zig
/home/alexrp/Sources/ziglang/zig/doc/langref/test_failed_int_to_float_coercion.zig:4:24: error: expected type 'f32', found 'u25'
const float: f32 = int;
^~~

类型强制转换:浮点数转整数

此处产生编译错误是合理的,因为表达式存在歧义,编译器在强制转换方面有两种选择。

  • 将 54.0 转换为 comptime_int,得到 @as(comptime_int, 10),再转换为 @as(f32, 10)
  • 将 5 转换为 comptime_float,得到 @as(comptime_float, 10.8),再转换为 @as(f32, 10.8)
test_ambiguous_coercion.zig
// 编译时将浮点数强制转换为整数
test "implicit cast to comptime_int" {
const f: f32 = 54.0 / 5;
_ = f;
}
命令行
$ zig test test_ambiguous_coercion.zig
/home/alexrp/Sources/ziglang/zig/doc/langref/test_ambiguous_coercion.zig:3:25: error: ambiguous coercion of division operands 'comptime_float' and 'comptime_int'; non-zero remainder '4'
const f: f32 = 54.0 / 5;
~~~~~^~~

类型强制转换:切片、数组与指针

test_coerce_slices_arrays_and_pointers.zig
const std = @import("std");
const expectEqual = std.testing.expectEqual;
const expectEqualStrings = std.testing.expectEqualStrings;
const expectEqualSlices = std.testing.expectEqualSlices;
// 指向数组的常量指针可以赋值给元素类型带有
// const 修饰符的切片。这对字符串字面量
// 尤其有用。
test "*const [N]T to []const T" {
const x1: []const u8 = "hello";
const x2: []const u8 = &[5]u8{ 'h', 'e', 'l', 'l', 111 };
try expectEqualStrings(x1, x2);
const y: []const f32 = &[2]f32{ 1.2, 3.4 };
try expectEqual(1.2, y[0]);
}
// 同样,目标类型为错误联合时也适用。
test "*const [N]T to E![]const T" {
const x1: anyerror![]const u8 = "hello";
const x2: anyerror![]const u8 = &[5]u8{ 'h', 'e', 'l', 'l', 111 };
try expectEqualStrings(try x1, try x2);
const y: anyerror![]const f32 = &[2]f32{ 1.2, 3.4 };
try expectEqual(1.2, (try y)[0]);
}
// 同样,目标类型为可选类型时也适用。
test "*const [N]T to ?[]const T" {
const x1: ?[]const u8 = "hello";
const x2: ?[]const u8 = &[5]u8{ 'h', 'e', 'l', 'l', 111 };
try expectEqualStrings(x1.?, x2.?);
const y: ?[]const f32 = &[2]f32{ 1.2, 3.4 };
try expectEqual(1.2, y.?[0]);
}
// 此转换中,数组长度成为切片长度。
test "*[N]T to []T" {
var buf: [5]u8 = "hello".*;
const x: []u8 = &buf;
try expectEqualStrings("hello", x);
const buf2 = [2]f32{ 1.2, 3.4 };
const x2: []const f32 = &buf2;
try expectEqualSlices(f32, &[2]f32{ 1.2, 3.4 }, x2);
}
// 指向数组的单项指针可以强制转换为多项指针。
test "*[N]T to [*]T" {
var buf: [5]u8 = "hello".*;
const x: [*]u8 = &buf;
try expectEqual('o', x[4]);
// x[5] 会造成未捕获的越界指针解引用!
}
// 同样,目标类型为可选类型时也适用。
test "*[N]T to ?[*]T" {
var buf: [5]u8 = "hello".*;
const x: ?[*]u8 = &buf;
try expectEqual('o', x.?[4]);
}
// 单项指针可以转换为长度为 1 的单项数组。
test "*T to *[1]T" {
var x: i32 = 1234;
const y: *[1]i32 = &x;
const z: [*]i32 = y;
try expectEqual(1234, z[0]);
}
// 哨兵终止切片可以强制转换为哨兵终止指针
test "[:x]T to [*:x]T" {
const buf: [:0]const u8 = "hello";
const buf2: [*:0]const u8 = buf;
try expectEqual('o', buf2[4]);
}
命令行
$ zig test test_coerce_slices_arrays_and_pointers.zig
1/8 test_coerce_slices_arrays_and_pointers.test.*const [N]T to []const T...OK
2/8 test_coerce_slices_arrays_and_pointers.test.*const [N]T to E![]const T...OK
3/8 test_coerce_slices_arrays_and_pointers.test.*const [N]T to ?[]const T...OK
4/8 test_coerce_slices_arrays_and_pointers.test.*[N]T to []T...OK
5/8 test_coerce_slices_arrays_and_pointers.test.*[N]T to [*]T...OK
6/8 test_coerce_slices_arrays_and_pointers.test.*[N]T to ?[*]T...OK
7/8 test_coerce_slices_arrays_and_pointers.test.*T to *[1]T...OK
8/8 test_coerce_slices_arrays_and_pointers.test.[:x]T to [*:x]T...OK
All 8 tests passed.

另见:

类型强制转换:可选值

可选类型的载荷类型及 null 都可以强制转换为该可选类型。

test_coerce_optionals.zig
const std = @import("std");
const expectEqual = std.testing.expectEqual;
test "coerce to optionals" {
const x: ?i32 = 1234;
const y: ?i32 = null;
try expectEqual(1234, x.?);
try expectEqual(null, y);
}
命令行
$ zig test test_coerce_optionals.zig
1/1 test_coerce_optionals.test.coerce to optionals...OK
All 1 tests passed.

可选类型嵌套在错误联合类型中也同样有效:

test_coerce_optional_wrapped_error_union.zig
const std = @import("std");
const expectEqual = std.testing.expectEqual;
test "coerce to optionals wrapped in error union" {
const x: anyerror!?i32 = 1234;
const y: anyerror!?i32 = null;
try expectEqual(1234, (try x).?);
try expectEqual(null, (try y));
}
命令行
$ zig test test_coerce_optional_wrapped_error_union.zig
1/1 test_coerce_optional_wrapped_error_union.test.coerce to optionals wrapped in error union...OK
All 1 tests passed.

类型强制转换:错误联合

错误联合类型的载荷类型及其错误集合类型都可以强制转换为该错误联合类型:

test_coerce_to_error_union.zig
const std = @import("std");
const expectEqual = std.testing.expectEqual;
test "coercion to error unions" {
const x: anyerror!i32 = 1234;
const y: anyerror!i32 = error.Failure;
try expectEqual(1234, (try x));
try std.testing.expectError(error.Failure, y);
}
命令行
$ zig test test_coerce_to_error_union.zig
1/1 test_coerce_to_error_union.test.coercion to error unions...OK
All 1 tests passed.

类型强制转换:编译时已知数值

如果在编译时已知某个数可以由目标类型表示,就可以强制转换:

test_coerce_large_to_small.zig
const std = @import("std");
const expectEqual = std.testing.expectEqual;
test "coercing large integer type to smaller one when value is comptime-known to fit" {
const x: u64 = 255;
const y: u8 = x;
try expectEqual(255, y);
}
命令行
$ zig test test_coerce_large_to_small.zig
1/1 test_coerce_large_to_small.test.coercing large integer type to smaller one when value is comptime-known to fit...OK
All 1 tests passed.

类型强制转换:联合与枚举

标记联合可以强制转换为枚举;如果在编译时已知枚举对应联合中的某个字段,且该字段类型只有一个可能值(例如 void),枚举也可以强制转换为标记联合:

test_coerce_unions_enums.zig
const std = @import("std");
const expectEqual = std.testing.expectEqual;
const E = enum {
one,
two,
three,
};
const U = union(E) {
one: i32,
two: f32,
three,
};
const U2 = union(enum) {
a: void,
b: f32,
fn tag(self: U2) usize {
switch (self) {
.a => return 1,
.b => return 2,
}
}
};
test "coercion between unions and enums" {
const u = U{ .two = 12.34 };
const e: E = u; // 将联合强制转换为枚举
try expectEqual(E.two, e);
const three = E.three;
const u_2: U = three; // 将枚举强制转换为联合
try expectEqual(E.three, u_2);
const u_3: U = .three; // 将枚举字面量强制转换为联合
try expectEqual(E.three, u_3);
const u_4: U2 = .a; // 将枚举字面量强制转换为使用推导枚举标记类型的联合。
try expectEqual(1, u_4.tag());
// 以下示例无效。
// 错误:从枚举 '@EnumLiteral()' 强制转换为联合 'test_coerce_unions_enum.U2' 时,必须初始化类型为 'f32' 的字段 'b'
//var u_5: U2 = .b;
//try expectEqual(2, u_5.tag());
}
命令行
$ zig test test_coerce_unions_enums.zig
1/1 test_coerce_unions_enums.test.coercion between unions and enums...OK
All 1 tests passed.

另见:

类型强制转换:undefined

undefined 可以强制转换为任意类型。

类型强制转换:元组转数组

如果所有字段类型相同,元组可以强制转换为数组。

test_coerce_tuples_arrays.zig
const std = @import("std");
const expectEqual = std.testing.expectEqual;
const Tuple = struct { u8, u8 };
test "coercion from homogeneous tuple to array" {
const tuple: Tuple = .{ 5, 6 };
const array: [2]u8 = tuple;
_ = array;
}
命令行
$ zig test test_coerce_tuples_arrays.zig
1/1 test_coerce_tuples_arrays.test.coercion from homogeneous tuple to array...OK
All 1 tests passed.

显式类型转换

显式类型转换通过内置函数完成。

某些显式转换若使用不当,会破坏类型安全。

某些显式转换会执行语言级断言。

某些显式转换在运行时不执行操作。

同级类型解析

以下位置会发生同级类型解析:

这种类型解析会选择一个所有同级类型都能强制转换到的类型。例如:

test_peer_type_resolution.zig
const std = @import("std");
const expectEqual = std.testing.expectEqual;
const expectEqualStrings = std.testing.expectEqualStrings;
test "peer resolve int widening" {
const a: i8 = 12;
const b: i16 = 34;
const c = a + b;
try expectEqual(46, c);
try expectEqual(i16, @TypeOf(c));
}
test "peer resolve small int and float" {
// 这仅适用于可以强制转换到该浮点类型的整数类型。
// 更大的整数类型会导致编译错误,不会发生浮点类型扩宽。
var i: u8 = 12;
var f: f32 = 34;
_ = .{ &i, &f };
const x = i + f;
try expectEqual(x, 46.0);
try expectEqual(@TypeOf(x), f32);
}
test "peer resolve arrays of different size to const slice" {
try expectEqualStrings("true", boolToStr(true));
try expectEqualStrings("false", boolToStr(false));
try comptime expectEqualStrings("true", boolToStr(true));
try comptime expectEqualStrings("false", boolToStr(false));
}
fn boolToStr(b: bool) []const u8 {
return if (b) "true" else "false";
}
test "peer resolve array and const slice" {
try testPeerResolveArrayConstSlice(true);
try comptime testPeerResolveArrayConstSlice(true);
}
fn testPeerResolveArrayConstSlice(b: bool) !void {
const value1 = if (b) "aoeu" else @as([]const u8, "zz");
const value2 = if (b) @as([]const u8, "zz") else "aoeu";
try expectEqualStrings("aoeu", value1);
try expectEqualStrings("zz", value2);
}
test "peer type resolution: ?T and T" {
try expectEqual(0, peerTypeTAndOptionalT(true, false).?);
try expectEqual(3, peerTypeTAndOptionalT(false, false).?);
comptime {
try expectEqual(0, peerTypeTAndOptionalT(true, false).?);
try expectEqual(3, peerTypeTAndOptionalT(false, false).?);
}
}
fn peerTypeTAndOptionalT(c: bool, b: bool) ?usize {
if (c) {
return if (b) null else @as(usize, 0);
}
return @as(usize, 3);
}
test "peer type resolution: *[0]u8 and []const u8" {
try expectEqual(0, peerTypeEmptyArrayAndSlice(true, "hi").len);
try expectEqual(1, peerTypeEmptyArrayAndSlice(false, "hi").len);
comptime {
try expectEqual(0, peerTypeEmptyArrayAndSlice(true, "hi").len);
try expectEqual(1, peerTypeEmptyArrayAndSlice(false, "hi").len);
}
}
fn peerTypeEmptyArrayAndSlice(a: bool, slice: []const u8) []const u8 {
if (a) {
return &[_]u8{};
}
return slice[0..1];
}
test "peer type resolution: *[0]u8, []const u8, and anyerror![]u8" {
{
var data = "hi".*;
const slice = data[0..];
try expectEqual(0, (try peerTypeEmptyArrayAndSliceAndError(true, slice)).len);
try expectEqual(1, (try peerTypeEmptyArrayAndSliceAndError(false, slice)).len);
}
comptime {
var data = "hi".*;
const slice = data[0..];
try expectEqual(0, (try peerTypeEmptyArrayAndSliceAndError(true, slice)).len);
try expectEqual(1, (try peerTypeEmptyArrayAndSliceAndError(false, slice)).len);
}
}
fn peerTypeEmptyArrayAndSliceAndError(a: bool, slice: []u8) anyerror![]u8 {
if (a) {
return &[_]u8{};
}
return slice[0..1];
}
test "peer type resolution: *const T and ?*T" {
const a: *const usize = @ptrFromInt(0x12345678);
const b: ?*usize = @ptrFromInt(0x12345678);
try expectEqual(a, b);
try expectEqual(b, a);
}
test "peer type resolution: error union switch" {
// 只有错误分支直接是 switch 表达式时,无错误分支与错误分支才视为同级;
// 模式 `if (x) {...} else |err| blk: { switch (err) {...} }` 不会将
// 无错误分支和错误分支视为同级。
var a: error{ A, B, C }!u32 = 0;
_ = &a;
const b = if (a) |x|
x + 3
else |err| switch (err) {
error.A => 0,
error.B => 1,
error.C => null,
};
try expectEqual(?u32, @TypeOf(b));
// 只有错误分支直接是 switch 表达式时,无错误分支与错误分支才视为同级;
// 模式 `x catch |err| blk: { switch (err) {...} }` 不会将解包后的 `x`
// 与错误分支视为同级。
const c = a catch |err| switch (err) {
error.A => 0,
error.B => 1,
error.C => null,
};
try expectEqual(?u32, @TypeOf(c));
}
命令行
$ zig test test_peer_type_resolution.zig
1/9 test_peer_type_resolution.test.peer resolve int widening...OK
2/9 test_peer_type_resolution.test.peer resolve small int and float...OK
3/9 test_peer_type_resolution.test.peer resolve arrays of different size to const slice...OK
4/9 test_peer_type_resolution.test.peer resolve array and const slice...OK
5/9 test_peer_type_resolution.test.peer type resolution: ?T and T...OK
6/9 test_peer_type_resolution.test.peer type resolution: *[0]u8 and []const u8...OK
7/9 test_peer_type_resolution.test.peer type resolution: *[0]u8, []const u8, and anyerror![]u8...OK
8/9 test_peer_type_resolution.test.peer type resolution: *const T and ?*T...OK
9/9 test_peer_type_resolution.test.peer type resolution: error union switch...OK
All 9 tests passed.