gpt4 book ai didi

rust - 如何在Rust中将变量作为字符串文字传递?

转载 作者:行者123 更新时间:2023-12-03 11:40:54 24 4
gpt4 key购买 nike

我正在使用仅接受字符串文字的宏 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!宏的所有示例仅使用字符串文字进行演示。

最佳答案

你不能。这实际上是不可能的。文字是在程序源代码中逐字写入值的东西。

不要使用该宏,因为它不会执行您想要的操作(强调我的意思):

This crate provides hex! macro for converting hexadecimal string literal to byte array at compile time.



也许您想要 hex crate

也可以看看:
  • What is the difference between literals and non-literals, other than the fact that non-literals go into the heap?
  • What does the word "literal" mean?
  • How can I convert a hex string to a u8 slice?
  • Converting a hexadecimal string to a decimal integer
  • Decimal number to hexadecimal string
  • How to convert hex string to a float in Rust?
  • How do I convert a string to hex in Rust?
  • Show u8 slice in hex representation
  • 关于rust - 如何在Rust中将变量作为字符串文字传递?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61071308/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com