相关疑难解决方法(0)

如何将 Vec 解构为拥有所有权的变量?

我有一个结构

struct Foo {
    foo1: String,
    foo2: String,
    foo3: String,
    foo4: String,
    // ...
}
Run Code Online (Sandbox Code Playgroud)

我想Foo从向量创建一个实例。

let x = vec!["a".to_string(), "b".to_string(), "c".to_string(), "d".to_string()];
match x.as_slice() {
    &[ref a, ref b, ref c, ref d] => {
        let foo = Foo {
            foo1: a.to_string(),
            foo2: b.to_string(),
            foo3: c.to_string(),
            foo4: d.to_string(),
        };

    },
    _ => unreachable!(),
}
Run Code Online (Sandbox Code Playgroud)

我必须复制字符串吗?有没有更好的方法将向量解构为a, b, c,d并转移所有权?

事实上,我不介意x解构后被彻​​底摧毁。所以我希望除了切片之外还有向量的模式匹配。目前看来我们只能解构切片。

rust

8
推荐指数
1
解决办法
3321
查看次数

Result<()> 在 Rust 中是什么意思?

我正在查看std::env::current_dir函数文档,这引起了我的注意:

std::io::Result<()>
Run Code Online (Sandbox Code Playgroud)

我的理解是 Result 应该有 aT和 an E。你怎么能用它们代替()

rust rust-result

1
推荐指数
1
解决办法
158
查看次数

标签 统计

rust ×2

rust-result ×1