Is it possible to map a function over a Vec without allocating a new Vec?

后端 未结 3 1764
天涯浪人
天涯浪人 2020-12-11 04:38

I have the following:

enum SomeType {
    VariantA(String),
    VariantB(String, i32),
}

fn transform(x: SomeType) -> SomeType {
    // very complicated          


        
3条回答
  •  悲&欢浪女
    2020-12-11 05:05

    Your first problem is not map, it's transform.

    transform takes ownership of its argument, while Vec has ownership of its arguments. Either one has to give, and poking a hole in the Vec would be a bad idea: what if transform panics?


    The best fix, thus, is to change the signature of transform to:

    fn transform(x: &mut SomeType) { ... }
    

    then you can just do:

    for x in &mut data { transform(x) }
    

    Other solutions will be clunky, as they will need to deal with the fact that transform might panic.

提交回复
热议问题