如何将命令行参数分配给 Rust 中的静态变量

发布于 2025-01-12 17:29:27 字数 467 浏览 1 评论 0原文

我是 Rust 新手。我正在创建一个带有命令行参数的 Rust 二进制文件。我希望能够将命令行参数字符串用作整个应用程序的静态常量字符串。

这样做的正确方法是什么?

如果我声明某些静态内容并更新它,我就必须在使用它的所有地方使用 unsafe

如果我像下面一样使用 lazy_static ,我不确定如何使本地获取的 &argv[1] 可供 main 内声明的闭包访问

lazy_static! {
    static ref MYID: String = get_arg_value();
}

fn main() {

    let argsv: Vec<String> = std::env::args().collect();
    let get_arg_value = || -> String { argsv[1] }

}

I am new to Rust. I am creating a Rust binary that takes a command line argument. I want to be able to use the command line argument string as a static constant string for the entirety of the application.

What is the right approach to doing that?

If I declare something static and I update it I am having to use unsafe everywhere I use it.

If I use lazy_static like below, I am not sure how to make the locally acquired &argv[1] accessible to a closure declared inside main

lazy_static! {
    static ref MYID: String = get_arg_value();
}

fn main() {

    let argsv: Vec<String> = std::env::args().collect();
    let get_arg_value = || -> String { argsv[1] }

}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

夏末的微笑 2025-01-19 17:29:28

只需将代码放入 lazy_static! 中即可:

lazy_static! {
    static ref MID: String = {
        let argsv: Vec<_> = std::env::args().collect();
        argsv[1]
    };
}

但随后您会收到错误“无法移出索引”。因此,克隆字符串(它是一次性初始化,因此性能无关紧要):

lazy_static! {
    static ref MID: String = {
        let argsv: Vec<_> = std::env::args().collect();
        argsv[1].clone()
    };
}

请注意,您实际上并不需要 Vec - 您可以使用迭代器:

lazy_static! {
    static ref MID: String = std::env::args().nth(1).unwrap();
}

另请注意,最好使用once_cell它将成为 std 的一部分。

Just put the code inside the lazy_static!:

lazy_static! {
    static ref MID: String = {
        let argsv: Vec<_> = std::env::args().collect();
        argsv[1]
    };
}

But then you'll get an error "cannot move out of index". So clone the string (it's one-time initialization so perf doesn't matter):

lazy_static! {
    static ref MID: String = {
        let argsv: Vec<_> = std::env::args().collect();
        argsv[1].clone()
    };
}

Note that you don't really need the Vec - you can work with the iterator:

lazy_static! {
    static ref MID: String = std::env::args().nth(1).unwrap();
}

Also note that it's better to use once_cell as it's going to be part of std.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文