简体   繁体   English

有人可以解释这是如何工作的:const print = @import("std").debug.print;

[英]Could someone explain how this works: const print = @import("std").debug.print;

How can this const print variable behave like a function?这个 const 打印变量如何表现得像 function?

const print = @import("std").debug.print;
print("hello, world", .{});

I understand you can assign expressions to variables.我知道您可以将表达式分配给变量。 But this seems to behave like a precompiler macro in c/c++, I wouldn't have guessed that.但这似乎表现得像 c/c++ 中的预编译器宏,我不会猜到的。 Is it because "all variables declared in a comptime expression are implicitly comptime variables" and @ makes it a comptime expression, so it is evaluated before compilation, much like a macro would in c?是不是因为“在 comptime 表达式中声明的所有变量都是隐式 comptime 变量”并且 @ 使其成为 comptime 表达式,所以它在编译之前被评估,就像 c 中的宏一样? Could someone elaborate a bit?有人可以详细说明一下吗? This seems a very powerful feature.这似乎是一个非常强大的功能。

@ does not indicate a comptime expression; @不表示 comptime 表达式; rather @ prefixes built-in functions in Zig.而是@为 Zig 中的内置函数添加前缀。 @import returns a struct that provides access to the declarations made public by the imported file. @import返回一个结构,该结构提供对导入文件公开的声明的访问。

The expression @import("std").debug.print evaluates to the print function defined in the standard library file std/debug.zig ;表达式@import("std").debug.print的计算结果为标准库文件std/debug.zig中定义的print function; it is not the expression that is assigned to print in the posted code, but the function .它不是在发布的代码中分配给print表达式,而是function That is, the posted code works because print in OP code is actually a function. This can be seen by running the code below:也就是说,发布的代码有效,因为 OP 代码中的print实际上是 function。这可以通过运行以下代码看到:

const print = @import("std").debug.print;

pub fn main() void {
    print("@TypeOf print: {}\n", .{ @TypeOf(print) });
}

Results:结果:

$ zig run print_type.zig 
@TypeOf print: fn(comptime []const u8, anytype) void

Function Assignment Function 作业

OP has asked for another example of assigning a function that is not imported to an identifier: OP 要求提供另一个分配未导入标识符的 function 的示例:

const print = @import("std").debug.print;

fn my_function(msg: []const u8) void {
    print("{s}\n", .{ msg });
}

const my_function_alias = my_function;

pub fn main() void {
    const another_function_alias = my_function;
    const yet_another_function_alias = my_function_alias;

    my_function("mf");
    my_function_alias("mfa");
    another_function_alias("afa");
    yet_another_function_alias("yafa");
}

Program output:程序 output:

$ zig run function_assignment.zig 
mf
mfa
afa
yafa

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM