Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

advanced/reflection #225

giscus[bot] bot announced in Comments
Feb 24, 2025 · 2 comments · 1 reply
Discussion options

advanced/reflection

简单、快速地学习 Zig,ziglang中文教程,zig中文教程

https://course.ziglang.cc/advanced/reflection

You must be logged in to vote

Replies: 2 comments 1 reply

Comment options

其实 @hasDecl 还可用于判断 函数 是否存在。

pub fn main() !void {
 // if (@hasDecl(@This(), "foobar")) {} else @compileError("不存在这个函数");
 if (@hasDecl(@This(), "qwq")) {} else @compileError("编译通过");
}
fn qwq() void {}
You must be logged in to vote
1 reply
Comment options

是的,可以判断当前容器内的函数是否存在,但是如果是其他的容器,则只能探查 pub 修饰的函数

Comment options

@typeinfo(comptime T: type) std.builtin.Type
参数要求:T 必须是 编译期已知类型,即 comptime。

返回值:返回一个结构体,描述 T 的完整类型信息(std.builtin.Type),这是一种 结构化的类型反射。

原因:

@typeinfo 的目标是对类型本身进行编译期的结构性分析,比如你可能想用它来生成代码,或者在编译期做逻辑分支(如 switch (@typeinfo(T).Kind))。

所以它必须在 编译时完全知道类型的所有结构,Zig 才能生成相应的类型信息数据结构。

这也是为什么它需要参数 T 是 comptime 的。

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

AltStyle によって変換されたページ (->オリジナル) /