You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将[4][4]f32矩阵转换为[]const [4][4]f32切片?

将单个[4][4]f32矩阵转换为[]const [4][4]f32切片的Zig实现方法

要把单个[4][4]f32矩阵转换成[]const [4][4]f32类型的切片,你可以通过以下两种简单方式实现:

方法1:利用数组指针生成单元素切片

直接对原矩阵取指针后,使用切片语法截取仅包含该矩阵的范围:

print_matrix_slices(&matrix[0..1]);

&matrix[0..1]会生成一个指向原矩阵的切片,长度为1,完全匹配[]const [4][4]f32的类型要求。

方法2:创建临时单元素数组再转切片

先构造一个仅包含目标矩阵的临时数组,再将其转换为切片:

const matrix_slice = [_][4][4]f32{ matrix }[0..];
print_matrix_slices(matrix_slice);

[_][4][4]f32{ matrix }创建了一个长度为1的数组,后续[0..]将其转为完整切片,类型符合函数参数要求。

修改后的完整代码

const std = @import("std");

pub fn print_matrix_slices(m: []const [4][4]f32) void {
    for (m) |matrix| {
        print_matrix(matrix);
    }
}

pub fn print_matrix(m: [4][4]f32) void {
    for (m) |row| {
        for (row) |elem| {
            std.debug.print("{d} ", .{ elem });
        }
        std.debug.print("\n", .{});
    }
}

pub fn main() void {
    const matrix = [4][4]f32{
        [4]f32{ 4.0, 3.0, 2.0, 1.0 },
        [4]f32{ 8.0, 7.0, 6.0, 5.0 },
        [4]f32{ 12.0, 11.0, 10.0, 9.0 },
        [4]f32{ 16.0, 15.0, 14.0, 13.0 },
    };

    print_matrix(matrix);

    // 方法1实现
    print_matrix_slices(&matrix[0..1]);

    // 或者方法2实现
    // const matrix_slice = [_][4][4]f32{ matrix }[0..];
    // print_matrix_slices(matrix_slice);
}

内容的提问来源于stack exchange,提问作者Flecart

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 05:36:09