简体   繁体   English

了解 Rust tracking info(target: "") 宏和类型

[英]Understanding Rust tracing info(target: "") macro and types

I've been enjoying navigating Rust through its type system.我一直很喜欢通过其类型系统导航 Rust。 But when it goes into macros I find it difficult to follow.但是当它进入宏时,我发现很难理解。 In the below example, why is it ok to pass "target_name" to target but not assign it then pass the assignment in?在下面的示例中,为什么可以将"target_name"传递给target但不分配它然后传递分配? How do you navigate the macro in tracing such that the below is obvious to you?您如何在跟踪中导航宏以使以下内容对您很明显? I am asking this as much from a developer experience perspective as a programmer.我从开发人员经验的角度和程序员一样多地问这个问题。 (I'm definitely looking for a "teach a man to fish" style answer.) (我肯定在寻找“教人钓鱼”风格的答案。)

info!(target: "target_name", "message"); // fine, must be cast to &str?
let target_name = "target_name"; // must be cast to String?
info!(target: target_name, "message"); // not fine

The latter call results in:后一个调用导致:

error[E0435]: attempt to use a non-constant value in a constant
   |
44 |         info!(target: target_name, "message");
   |                       ^^^^^^^^^^^ non-constant value

Even if I switch to &target_name.as_str() which I believe should be constant (not growable like String ) the macro still fails with the same error.即使我切换到我认为应该是常量的&target_name.as_str() (不能像String那样增长),宏仍然会失败并出现相同的错误。 This is where my mental map is failing.这就是我的心理 map 失败的地方。 I can understand that the assumed type when assigning is wrong, but then when I recast it, why would it fail?我可以理解分配时假定的类型是错误的,但是当我重铸它时,它为什么会失败?

The solution here is to use a const with a type that's compatible with expectations, like:这里的解决方案是使用具有与预期兼容的类型的const ,例如:

const target_name : &str = "target_name";

You can usually view the source for these macros in the documentation , as shown here:您通常可以在文档中查看这些宏的源代码,如下所示:

#[macro_export(local_inner_macros)]
macro_rules! info {
    (target: $target:expr, $($arg:tt)+) => (
        log!(target: $target, $crate::Level::Info, $($arg)+)
    );
    ($($arg:tt)+) => (
        log!($crate::Level::Info, $($arg)+)
    )
}

That's just a wrapper around log!这只是log! , so it's not especially informative, and log! ,所以它不是特别有用,并且log! is just a wrapper around __private_api_log which is even less helpful.只是__private_api_log的一个包装器,它的帮助更小。

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

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