【问题标题】:rustc: argument must be a string literal [duplicate]rustc:参数必须是字符串文字[重复]
【发布时间】:2021-10-05 12:30:25
【问题描述】:

我有 test.rs:

const TEST: &'static str = "Test.bin";

fn main() {
    let x = include_bytes!(TEST);
}

rustc test.rs

如何解决这个错误?

error: argument must be a string literal

 --> test.rs:4:22
  |
4 |     let x = include_bytes!(TEST);
  |                      ^^^^

【问题讨论】:

  • 如何解决?答案就在问题中:在括号之间放置一个字符串文字。 let x = include_bytes!("test.bin");
  • 我需要把这个值从函数中取出来让与代码的交互更容易
  • 那你就不能使用这个宏了。你真的希望在二进制文件中包含一些动态的东西吗?
  • 等等,让我明白这一点,这个宏甚至不能接受静态字符串参数?那这是什么无用的bs?我的意思是,在函数中硬编码文件名是非常糟糕的做法,所以谁认为这是个好主意?

标签: string rust constants


【解决方案1】:

宏需要一个字符串文字,所以它不能是一个变量:

include_bytes!("Test.bin");

或者,您也可以创建一个宏来扩展为所需的值:

macro_rules! test_bin {
    // `()` indicates that the macro takes no argument.
    () => {
        "Test.bin"
    };
}

fn main() {
    let x = include_bytes!(test_bin!());
}

Playground

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-05
    • 2017-05-06
    • 2019-11-04
    • 1970-01-01
    • 1970-01-01
    • 2020-09-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多