rust - 如何使用引用解构元组结构

标签 rust

我正在尝试使用 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/

相关文章:

rust - 我可以只为没有包的代码包含调试信息吗?

generics - 使用泛型作为集合中函数​​的参数

rust - 如何将方法作为回调/处理程序参数传递给函数? [复制]

rust - `paint_evm::Event` 未针对 `Event` 实现

rust - 在 Rust 中返回包含引用的对象

rust - 使用 if let 时如何指定无法推断的类型?

rust - 函数返回 serde 反序列化类型时如何修复生命周期错误?

encryption - 如何为AES加密生成随 secret 钥?

rust - 读取或写入整个 32 位字,即使我们只引用其中的一部分,是否会导致未定义的行为?

error-handling - 当函数没有返回成功值时如何使用 Result?