Zig学习笔记

学习资料

const std = @import("std");
const print = std.debug.print;
 
pub fn main() !void {
    print("Hello {s} World.", .{"zig"});
}

代码案例

猜数字

const std = @import("std");
const print = std.debug.print;
const stdin = std.io.getStdIn().reader();
var stdout = std.io.getStdOut().writer();
var stderr = std.io.getStdErr().writer();
 
pub fn main() !void {
    // 生成随机数
    //var rand = std.rand.DefaultPrng.init(@as(u64, @abs(std.time.timestamp())));
    const rand = std.crypto.random;
    const number = rand.intRangeAtMost(u8, 1, 100);
 
    print("欢迎来到猜数字游戏!请输入一个 1 到 100 之间的数字:", .{});
 
    while (true) {
        // 读取用户输入
        var buffer: [20]u8 = undefined;
        const input = stdin.readUntilDelimiter(&buffer, '\n') catch {
            @panic("Failed to read line");
        };
        // 转换输入为数字
        const guess = std.fmt.parseInt(u8, input, 10) catch {
            try stderr.print("无效输入,请输入1到100的数字: ", .{});
            continue;
        };
 
        if (guess < 1 or guess > 100) {
            try stderr.print("无效输入,请输入1到100的数字: ", .{});
        } else if (guess < number) {
            try stdout.print("< 小了\n", .{});
        } else if (guess > number) {
            try stdout.print("> 大了\n", .{});
        } else {
            try stdout.print("= 恭喜你,猜对了,幸运数字: {}\n", .{number});
            break;
        }
    }
}

算力机柜计算

const std = @import("std");
 
pub fn main() !void {
    const H100 = 16.0; // 单卡2p * 8卡,声明为浮点数
    const N4090 = 2.64; // 单卡 0.33p * 8卡,声明为浮点数
    const N = 192; // 总共是192个机柜
    var i: f32 = 0;
    //for (0..N) |i| {
    while (i <= N) : (i += 1) {
        //const t100 = @as(f64, i) * 4.0 * H100; // Convert i to f64
        const t100 = i * 4 * H100; // Convert i to f64
        const t4090 = (N - i) * 8 * N4090; // Convert N - i to f64
 
        if (t100 + t4090 > 4000) { // Use floating-point comparison
            std.debug.print("{d}个机柜的H100的算力是{d}P, 其它{d}个机柜的4090算力是{d}Ps\n", .{ i, t100, N - i, t4090 });
            break;
        }
    }
}

借鉴学习的代码

const std = @import("std");
const deb = std.debug;
const io = std.io;
const print = deb.print;
const stdoutf = io.getStdOut().writer();
var bw = io.bufferedWriter(stdoutf);
const stdout = bw.writer();
 
const arrayList = std.ArrayList;
const sheap = std.heap;
const config=.{.safety=true};
var gpa = sheap.GeneralPurposeAllocator(config){};
const gpaallocator = gpa.allocator();
 
const Vec = struct {
    x: f32,
    y: f32,
 
    pub fn init(xa:f32,ya:f32) Vec {
        return Vec { .x=xa + 0.1 , .y=ya + 0.2};
    }
 
    pub fn printx(v:Vec) void {
        print("{e}\n",.{v.x});
    }
 
};
 
const Month = enum {
    January,
    February,
    March,
};
 
fn myadd(a:i32,b:i32) i32 {
return a+b;
}
 
fn myprint(s:[] const u8) void {
    print("string:{s}",.{s});
}
 
pub fn range(len: usize) []const u0 {
    return @as([*]u0, undefined)[0..len];
}
 
const  myunion = union(enum) {
    i:i32,
    f:f32,
};
 
fn printunion(u:myunion)  void {
    switch(u) {
        .i => |i| print("Integer : {d}\n",.{i}),
        .f => |f| print("Float : {e}\n",.{f}),
    }
}
 
const myerrors= error { MyError,MyError2};
 
fn testerror(succeed:bool) myerrors!bool {
    if(!succeed) {
        return myerrors.MyError; 
    }
    else {
        return true;
    }
 
}
 
pub fn main() !void {
 
    var arrx:[10]u32=undefined;
    arrx[2]=4;
    print("{d}\n",.{arrx[2]});
 
    var x: i32=321;
    var px: *i32=&x;
    print("{d}\n",.{px.*});
 
    var ov: ?u32=null;
    if(ov)|value|{
        print("Value : {d}\n",.{value});
    }
    else {
        print("isnull\n",.{});
    }
    ov=88;
    if(ov)|value|{
        print("Value : {d}\n",.{value});
    }
    else {
        print("isnull\n",.{});
    }
 
    const  r:bool = testerror(false) catch |err| blk: {
        if (err == myerrors.MyError) {
            break :blk false;
        }
        else {
            return;
        }
    };
    print("{any}\n",.{r});
 
    switch (15) {
        0...10 => pri{"0-10\n",.{}},
        15 => print("15\n",.{}),
        20 => print("20\n",.{}),
        else =>  print("Error\n",.{}),
    }
 
    print("Hello World1\n", .{});
    try stdout.print("Hello World2\n", .{});
    try bw.flush();
 
    const myvec = Vec.init(2.0,3.0);
    print("{e}\n", .{myvec.x});
    myvec.printx();
 
    var vv: i32 = 123;
    print("{d}\n", .{vv});
 
    var month:Month=.January;
    print("Month:{}\n",.{month});
 
    print("Add : {d}\n", .{myadd(123,456)});
 
    myprint("Mystring\n");
 
    const m1:myunion=myunion{.f=2.3};
    const m2:myunion=myunion{.i=5};
    printunion(m1);
    printunion(m2);
 
    var list = arrayList(u8).init(gpaallocator);
    defer list.deinit();
    try list.append('C');
    try list.append('A');
    try list.append('T');
    _ =list.pop();
    for (list.toOwnedSlice()) |elem,index| {
        print("by val: {d} : {c} \n", .{index,elem});
    }