【问题标题】:How to pass a variable as a string literal in Rust?如何在 Rust 中将变量作为字符串文字传递?
【发布时间】:2020-07-19 03:07:59
【问题描述】:

我正在使用只接受字符串文字的宏 hex!。 我有一个从函数返回并存储在变量中的值。我无法对这些值进行硬编码并调用此函数。那么,如何使用变量调用hex! 宏呢?

这是我的工作代码:

let account: AccountId32 = hex_literal::hex!["d43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d"].into();

这是我遇到错误的代码:

let account_id = "d43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d";
let account: AccountId32 = hex_literal::hex!(&account_id).into();

错误是:

error: proc-macro derive panicked
  --> src/examples/example_substratekitties.rs:49:32
   |
49 |     let account: AccountId32 = hex_literal::hex!(&account_id).into();
   |                                ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
   |
   = help: message: expected one string literal
   = note: this warning originates in a macro outside of the current crate (in Nightly builds, run with -Z external-macro-backtrace for more info)

hex! 宏的所有示例仅使用字符串文字进行演示。

【问题讨论】:

标签: rust


【解决方案1】:

你不能。 字面意思是不可能的。字面量是在程序的源代码中逐字写入值的东西。

不要使用那个宏,因为它不能做你想做的事(强调我的):

此 crate 提供 hex! 宏,用于将十六进制字符串文字转换为字节数组在编译时

也许你想要hex crate

另见:

【讨论】:

    猜你喜欢
    • 2019-07-13
    • 2011-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-28
    • 1970-01-01
    • 1970-01-01
    • 2012-04-17
    相关资源
    最近更新 更多