rustc:参数必须是字符串字面值。

3

我有一个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"); - Denys Séguret
我需要将这个值从函数中取出,以便更轻松地与代码交互。 - user16564170
那么你不能使用这个宏。你真的希望在二进制文件中包含一些动态的东西吗? - Denys Séguret
1
等一下,让我确认一下,这个宏甚至不能接受一个静态字符串参数?这是什么无用的东西?我的意思是,在函数内部硬编码文件名是非常不好的做法,那么谁认为这是一个好主意呢? - Spectraljump
1个回答

4
该宏需要一个字符串字面量,因此不能是变量:
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!());
}

游乐场


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接