[英]why do user defined types in zig need to be const?
如果我需要在 Zig 中聲明一個結構體,我必須在它前面加上一個const
const Arith = struct {
x: i32,
y: i32,
fn add(self: *Arith) i32 {
return self.x + self.y;
}
};
test "struct test" {
var testArith = Arith{
.x = 9,
.y = 9,
};
expect(testArith.add() == 18);
}
但是它可以通過var
和const
兩種方式進行初始化,那么為什么類型聲明需要一個常量關鍵字,因為它只對結構的實例是否為const
很重要?
需要是const
因為根作用域中的求值順序是未定義的,並且因為 type type
的變量只能存在於編譯器中(沒有內存表示,編譯器無法生成它的二進制表示)。 但是您可以在其他范圍內使用var
:
comptime {
var T = struct { value: u64 };
const x: T = .{ .value = 3 };
T = struct { ok: bool };
const y: T = .{ .ok = true };
@compileLog(x.value); // <- 3
@compileLog(y.ok); // <- true
}
在剩下的答案中,我會詳細解釋。
const Arith = struct {...};
創建推斷類型的常量變量。 在這種情況下,變量Arith
類型為type
:
const Arith = struct {...};
comptime {
@compileLog(@TypeOf(Arith)); // <- type
}
這與將變量聲明為相同:
const Arith: type = struct {...};
你也可以用var
創建一個變量
例子:
comptime {
var Arith = struct {...};
}
comptime {
var Arith: type = struct {...};
}
fn main() !void {
comptime var Arith = struct {...};
}
fn main() !void {
var Arith: type = struct {...};
}
fn main() !void {
comptime var Arith: type = struct {...};
}
因為是一個變量,你可以修改它:
comptime {
var T = u64;
T = bool;
@compileLog(T); // <-- bool
}
有類型,只能住在編譯器,如: type
或具有類型的字段結構anytype
或其他類型COMPTIME。
在type
的情況下,這會使編譯器將var x: type
解釋為comptime var x: type
。
然后,考慮以下代碼:
var T = struct { value: u64 }; // <- Compiler error
comptime {
const x: T = .{ .value = 3 };
}
error: variable of type 'type' must be constant
由於根作用域中的求值順序未定義,編譯器強制在二進制文件中創建一個全局變量,但類型type
沒有內存表示。 因此,編譯器會引發錯誤。
由於Arith
屬於類型type
因此必須將其聲明為常量,因為編譯器希望它是。 這可以通過將類型聲明更改為 this 並運行程序來檢查
var Arith = struct {
x: i32,
y: i32,
fn add(self: *Arith) i32 {
return self.x + self.y;
}
};
這將導致錯誤error: variable of type 'type' must be constant
同樣在 Zig 中,我們需要在名稱之前使用const
或var
否則將其視為無效標記。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.