Zig 慣用法之命名規則

一般來說:

這樣當我們看到 file_path 就知道這是一個變量, FilePath 是一個類型。

有一個例外的情況,就是返回類型的函數,它們採用 PascalCase ,例如:

    pub fn ArrayList(comptime T: type) type {
        return ArrayListAligned(T, null);
    }
    
    pub fn StringHashMap(comptime V: type) type {
        return HashMap([]const u8, V, StringContext, default_max_load_percentage);
    }

這些函數通常用來實現泛型。

與之類似,文件名通常是 lowercase_with_underscore 風格,但是,如果把文件作爲 struct 使用時,那就應該採用 PascalCase 風格,比如

    // Foo.zig
    pub var a: usize = 1;
    
    b: usize,
    
    const Self = @This();
    
    pub fn inc(self: *Self) void {
        self.b += 1;
    }
    
    // main.zig
    const Foo = @import("Foo.zig");
    
    pub fn main() !void {
        const foo = Foo{ .b = 100 };
        std.debug.print("Type of Foo is {any}, foo is {any}\n", .{
            @TypeOf(Foo),
            @TypeOf(foo),
        });
        foo.inc();
        std.debug.print("foo.b = {d}\n", .{foo.b});
    }

摘抄自:https://github.com/zigcc/zig-idioms

本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源https://mp.weixin.qq.com/s/kQabIzMN1puO8GJgpXE6zw