相关疑难解决方法(0)

如何在不复制向量的情况下将Vec <T>转换为Vec <U>?

我想将a转换Vec<T>Vec<U>where T某种原语,并且U是一种新类型T:struct U(T).

我试过这样的事情:

struct Foo(u32);

fn do_something_using_foo(buffer: &mut Vec<Foo>) {}

fn main() {
    let buffer: Vec<u32> = vec![0; 100];

    do_something_using_foo(&mut buffer as Vec<Foo>);
}
Run Code Online (Sandbox Code Playgroud)

我不想复制矢量,我想u32在newtype中包装字段Foo.

这给出了错误:

error[E0308]: mismatched types
 --> main.rs:8:28
  |
8 |     do_something_using_foo(&mut buffer as Vec<Foo>);
  |                            ^^^^^^^^^^^^^^^^^^^^^^^ expected mutable reference, found struct `std::vec::Vec`
  |
  = note: expected type `&mut std::vec::Vec<Foo>`
         found type `std::vec::Vec<Foo>`
  = help: try with `&mut &mut buffer as …
Run Code Online (Sandbox Code Playgroud)

rust

6
推荐指数
2
解决办法
534
查看次数

标签 统计

rust ×1