Zig : 关于@Vector,slice,array,arraylist实例

张开发
2026/4/10 4:45:08 15 分钟阅读

分享文章

Zig : 关于@Vector,slice,array,arraylist实例
最近在看Zig是一个有意思的语言。以一个字符串容器为例来尝试了解一下Zig和其它语言有什么不同。一、代码const std import(std);const print std.debug.print;pub fn main() !void{try print_arraylist();_ print_array();_ print_slice();_ print_vector();}fn print_slice()void{print(-------------print_slice-----------\n,.{});// names : strings: []const []const u8, const names :[]const []const u8 [_][]const u8{rust,zig,julia,}; for (names)|name|{print(name :{s}\n,.{name});}}fn print_array()void{print(-------------print_array-----------\n,.{});const names [3][]const u8{rust,zig,julia,}; for (names)|name|{print(name :{s}\n,.{name});}}fn print_arraylist()!void{print(-------------print_arraylist-----------\n,.{});const ArrayList std.ArrayList;const allocator std.heap.page_allocator;varnames:ArrayList([]const u8) .empty;defer names.deinit(allocator);try names.append(allocator,rust);try names.append(allocator,zig);try names.append(allocator,julia);for (names.items) |name|{std.debug.print(name {s}\n, .{name});}}fn print_vector() void{print(-------------print_vector-----------\n,.{});const _names [3][*:0]const u8{rust,zig,julia,};constlength:u32 _names.len;constnames:Vector(length,[*:0]const u8) _names;//Vector只能索引 vari:u8 0;while(ilength):(i1){const name names[i];print(name_{d} :{s}\n,.{i,name});}}上面ArrayList是动态可变的数组其它的是固定长度的类型有数组有切片也有向量。二、运行结果(venv)PSD:\my_program\zig\my_first_zig zig run option.zig -------------print_arraylist----------- name rust name zig name julia -------------print_array-----------name:rustname:zigname:julia -------------print_slice-----------name:rustname:zigname:julia -------------print_vector-----------name_0:rustname_1:zigname_2:julia

更多文章