gpt4 book ai didi

rust - 匹配一个拥有的变量,然后再次访问该变量

转载 作者:行者123 更新时间:2023-11-29 08:00:56 25 4
gpt4 key购买 nike

我想做点什么

enum A {
Type1 {
s: String
// ... some more fields
}
// ... some more variants
}

impl A {
fn consume(self) { println!("Consumed!"); }
}

fn fails() {
let b = A::Type1 { s: String::from("Arbitrary string") };

match b {
A::Type1 {
s, // (value moved here)
// ... more fields
} => {
let l = s.len(); // Something using the field from the enum
if l > 3 {
s.into_bytes(); // do something that requires ownership of s
} else {
b.consume(); // Value used here after move
}
}
// ... more cases
}
}

但是,因为我在匹配案例中解构了 b,所以我无法在匹配主体中访问它。

我可以从字段中重建b,但是当b 有很多字段时,这显然不是理想的。有什么办法可以解决这个问题而不必重建 b

最佳答案

不,你(几乎字面上)不能既吃蛋糕又吃蛋糕。解构该值后,该值将不再存在。


当发生非词法生命周期时,您可以结合使用 NLL 和匹配守卫来首先防止获取所有权:

#![feature(nll)]

enum A {
Type1 { s: String },
}

impl A {
fn consume(self) {
println!("Consumed!");
}
}

fn main() {
let b = A::Type1 {
s: String::from("Arbitrary string"),
};

match b {
A::Type1 { ref s } if s.len() <= 3 => {
b.consume();
}
A::Type1 { s } => {
s.into_bytes();
}
}
}

关于rust - 匹配一个拥有的变量,然后再次访问该变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48889779/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com