HelloWorld
Zig 是一种强类型编译语言。它支持泛型,具有强大的编译时元编程功能,并且不包含垃圾收集器。许多人认为 Zig 是 C 的现代替代品。因此,该语言的语法与 C 类似,比较明显的就是以分号结尾的语句和以花括号分隔的块。
const std = @import("std");
//使用@引用编辑器自带模块
// zig test 文件.zig 运行测试 会显示:ALL 1 test passed
const expect = std.testing.expect;
test "always success" {
try expect(true);
}
//每个zig程序输出都要有的main入口
pub fn main() void {
std.debug.print("Hello, {s}!\n", .{"World"});
}
赋值语法
(const|var) identifier[: type] = value
其中const为存储不可改变值的常量,var为存储可变值的变量,: type为设定改值的数据类型
在可能的情况下,const
价值观优先于var
价值。
常量和变量必须有一个值。如果无法给出已知值, undefined
则只要提供类型注释,就可以使用强制转换为任何类型的值。
const std = @import("std");
const name = "genshin";
var username = "Liliya";
pub fn main() void {
std.debug.print("My name is {s} and i love play {s}",.{username,name});
}
数组
在zig中数组使用[N]T代表数组,其中N为数组数量,可以使用_
代替,T是数组类型
const std = @import("std");
const name = "genshin";
var username = "Liliya";
const array = [_]i32{ 1, 2, 3, 4, 6, 7, 8 };
//使用[start...end]切片
const cut = array[0..4];
const arrayOneBu = [_]u8{ 'd', 'i', 'o', 'k', 'b', 'i', 'g' };
const arrayChinese = [_]u16{ '顶', '硬', '上', '的', '男', '子', '汉' };
pub fn main() void {
std.debug.print("My name is {s} and i love play {s}\n", .{ username, name });
std.debug.print("array count:{d},get NO.2 Str is {d}\n", .{ array.len, array[2] });
std.debug.print("array count:{d},get NO.2 Str is {u}\n", .{ arrayOneBu.len, arrayOneBu[2] });
std.debug.print("array count:{d},get NO.2 Str is {u}\n", .{ arrayChinese.len, arrayChinese[7] });
std.debug.print("array count:{d},get NO.2 Str is {any}", .{ cut.len, cut });
}
test测试函数
用于在没有main入口时检查代码是否可运行:
const std = @import("std");
test "test add one" {
try std.testing.expect(addOne(42) == 43);
}
test addOne {
try std.testing.expect(addOne(42) == 43);
}
fn addOne(number: i32) i32 {
return number + 1;
}
-----------------------------------------------------------------------------------------
PS E:\学习\zigsd> zig test .\testMethod.zig
All 2 tests passed.