![](/img/trans.png)
[英]What's the right way to create OsStr(ing) from a FFI-returned slice?
[英]What's the correct way to convert from &str to OsStr?
我正在使用rust-fuse ,它將mount選項作為&[&std::ffi::os_str::OsStr]
。 看來我應該分割傳入的逗號分隔的選項字符串,我這樣做是:
mod fuse {
use std::ffi::OsStr;
pub fn mount(options: &[&OsStr]) {}
}
fn example(optstr: &str) {
let mut options: &[&str] = &[];
if optstr != "" {
options = optstr.split(",").collect::<Vec<_>>().as_slice();
}
fuse::mount(options)
}
出現以下錯誤:
error[E0308]: mismatched types
--> src/main.rs:12:17
|
12 | fuse::mount(options)
| ^^^^^^^ expected struct `std::ffi::OsStr`, found str
|
= note: expected type `&[&std::ffi::OsStr]`
found type `&[&str]`
我的印象是所有&str
都是OsStr
,但是我對Rust還是OsStr
的,所以我想那是錯誤的。
使用OsStr::new
:
use std::ffi::OsStr;
fn main() {
let a_string: &str = "Hello world";
let an_os_str: &OsStr = OsStr::new(a_string);
println!("{:?}", an_os_str);
}
請注意,顯式類型規范不是必需的,我只是出於教育目的將其包括在內。
在您的特定情況下:
let options: Vec<_> = optstr.split(",").map(OsStr::new).collect();
fuse::mount(&options)
但是,實際上很少需要顯式地執行此操作。 大多數時候,函數接受實現AsRef<OsStr>
的類型。 這將使您無需考慮就可以傳遞更多類型。 您可能要考慮詢問維護者或向庫提交補丁,以使其更加通用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.