如何将命令行参数分配给 Rust 中的静态变量
我是 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
只需将代码放入
lazy_static!
中即可:但随后您会收到错误“无法移出索引”。因此,克隆字符串(它是一次性初始化,因此性能无关紧要):
请注意,您实际上并不需要
Vec
- 您可以使用迭代器:另请注意,最好使用
once_cell
为 它将成为std
的一部分。Just put the code inside the
lazy_static!
: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):
Note that you don't really need the
Vec
- you can work with the iterator:Also note that it's better to use
once_cell
as it's going to be part ofstd
.