无法使用本地创建的矢量,因为 "borrowed"

Can't use locally created vector because "borrowed"

由于错误,我无法获取向量的第一个元素,也无法更改结构设计。我尝试借用,但结构需要一个 ExtrudeGeometry。

#[wasm_bindgen]
pub fn toCollection(arr: js_sys::Array, r_type: String) -> JsValue {
    let n_arr: Vec<ExtrudeGeometry> = arr.into_serde().unwrap();
    if r_type == "GeometryCollection" {
        return JsValue::from_serde(&OutputGeometryCollection {
            collection: n_arr,
            r#type: r_type,
        })
        .unwrap();
    } else {
        let ex: ExtrudeGeometry = n_arr[0];
        return JsValue::from_serde(&OutputObject {
            data: ex,
            r#type: r_type,
        })
        .unwrap();
    }
}
error[E0507]: cannot move out of borrowed content
   --> src/lib.rs:308:39
    |
308 |             let ex: ExtrudeGeometry = n_arr[0];
    |                                       ^^^^^^^^
    |                                       |
    |        cannot move out of borrowed content
    |        help: consider borrowing here: `&n_arr[0]`

我在这个答案中假设 Rust 的所有权系统是已知的。你的 vector 拥有这些项目,所以如果你要第一个,你只能借用它,因为 vector 是由内存中连续的项目组成的。您不能使用索引符号从中随机删除项目。

如果你想拿第一个,你有3个选择:

  • 你不关心向量的剩余部分:你可以将它转换成一个迭代器并取第一个迭代的项目:

    vector
        .into_iter() // consume the vector to get an iterator
        .next() // get the first iterated item
        .unwrap()
    
  • 你关心剩下的,但不关心顺序,使用swap_remove:

    vector.swap_remove(0)
    
  • 您关心剩余部分和顺序:不要使用向量。我没有那个选择,你可以使用 remove,但这是一个 O(n) 函数。


顺便说一下,最后一个位置的 return 不是惯用语:

#[wasm_bindgen]
pub fn toCollection(arr: js_sys::Array, r_type: String) -> JsValue {
    let n_arr: Vec<ExtrudeGeometry> = arr.into_serde().unwrap();

    if r_type == "GeometryCollection" {
        JsValue::from_serde(&OutputGeometryCollection {
            collection: n_arr,
            r#type: r_type,
        })
        .unwrap()
    } else {
        let ex = n_arr.into_iter().next().unwrap();

        JsValue::from_serde(&OutputObject {
            data: ex,
            r#type: r_type,
        })
        .unwrap();
    }
}