我正在尝试使用 super 库来提出一些请求。 Headers::get()
方法返回 Option<&H>
, 其中H
是一个只有一个字段的元组结构。我可以使用 if let Some()
破坏Option
.但是我们如何解构 &H
?当然,我总是可以使用 .0
访问该字段,但我很好奇 Rust 是否有执行此操作的语法。
struct s(String);
fn f(input: &s) -> &s {
input
}
fn main() {
let my_struct1 = s("a".to_owned());
let s(foo) = my_struct1;
let my_struct2 = s("b".to_owned());
let &s(bar) = f(&my_struct2); // this does not work
let baz = &my_struct2.0; // this works
}
最佳答案
当您尝试编译它时,Rust 编译器会通过一条友好的消息告诉您如何修复错误:
error[E0507]: cannot move out of borrowed content
--> <anon>:11:9
|
11 | let &s(bar) = f(&my_struct2); // this does not work
| ^^^---^
| | |
| | hint: to prevent move, use `ref bar` or `ref mut bar`
| cannot move out of borrowed content
这需要告诉编译器您只需要引用结构中的字段;默认匹配将执行移动,原始结构值将不再有效。
让我们修正这个例子:
struct s(String);
fn f(input: &s) -> &s {
input
}
fn main() {
let my_struct1 = s("a".to_owned());
let s(foo) = my_struct1;
let my_struct2 = s("b".to_owned());
let &s(ref bar) = f(&my_struct2);
}
另一种方法是首先取消引用并删除 &
。我认为这在 Rust 中是首选:
struct s(String);
fn f(input: &s) -> &s {
input
}
fn main() {
let my_struct1 = s("a".to_owned());
let s(foo) = my_struct1;
let my_struct2 = s("b".to_owned());
let s(ref bar) = *f(&my_struct2);
}
关于rust - 如何使用引用解构元组结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40829552/