[英]struct definition with var instead of const in zig language
我現在正在學習zig
語言。 我已經看到了帶有const
關鍵字的結構定義,例如
const X = struct {
n: i32,
};
我的理解是const
是對var
的一種補充,后者允許改變,前者不允許。 但是用var
定義 struct 意味着什么?
var Y = struct {
n: i32,
};
這合法嗎? 我編譯,所以是的,它是。 但是這有什么意義和用途呢?
編譯是因為 zig 是惰性評估的。 因為沒有使用Y
,所以編譯器不會檢查它。
當你引用它時,編譯器會拋出一個錯誤:
var Y = struct {
n: i32,
};
comptime {
@compileLog(Y);
}
error: variable of type 'type' must be constant
var Y = struct {
^
var
是聲明變量。 當您在全局 scope 中使用var
時,會創建一個全局變量。
在你的情況下,
var Y = struct {
n: i32,
};
將Y
聲明為推斷類型的變量。 在這種情況下, Y
是 type type
的變量。
在 zig 中,只有 comptime 類型,即type
的情況。 類型為 comptime-only 類型的值只能存在於編譯器中,您不能在運行時1中創建該值。 因此,編譯器需要始終知道該值。
所以,因為Y
是一個全局變量。 您可以在運行時修改它。 這就是錯誤的原因。 Y
的值不能由二進制文件生成/存儲。
如果只存在於編譯器中,則有效
comptime {
var Y = struct {
n: i32,
};
Y = struct {
count: u32,
};
const concrete = Y { .count = 10 };
@compileLog(concrete.count);
}
| 10
1例如,考慮
const std = @import("std");
fn compilerKnown(arg: []const u8) type {
return u64;
}
pub fn main() !void {
var runtimeValue = "hello world";
std.debug.print("{}\n", .{ compilerKnown(runtimeValue) });
}
error: unable to evaluate constant expression
std.debug.print("{}\n", .{ compilerKnown(runtimeValue) });
^
這是一個錯誤,因為 zig 嘗試將 function compilerKnown
已知為二進制,但類型type
為 comptime-only,因此無法生成二進制。 特別是,無法為return u64
生成機器代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.