如何在 Rust 中解构和解引用元组

3
有没有一种方法可以在解构元组的同时在同一行上取消引用foobar,以简化以下代码?
let a = "a";
let b = "b";
let c = (&a, &b);

// Can we dereference here?
let (foo, bar) = c;

let foo_loc = *foo;
let bar_loc = *bar;
println!("{}", foo_loc);
println!("{}", bar_loc);
1个回答

5
你可以使用模式匹配引用:
fn main() {
    let a = "a";
    let b = "b";
    let c = (&a, &b);
    let (&foo, &bar) = c;
    println!("{}", foo);
    println!("{}", bar);
}

游乐场


这里是 Rust 的新手,想知道如果我们执行 let (foo, bar) = c.to_owned(); 是否会相同或类似? - heemayl
@heemayl 是的和不是,当移动 c 时,您已经在执行 to_owned。因此,为了解决他所问的问题,您仍需要进行模式匹配。 - Netwave
没问题,谢谢。 - heemayl
2
c.to_owned() 会调用 (&&str, &&str)ToOwned 实现,该实现由通用实现 impl<T> ToOwned for T where T: Clone 覆盖。因此,c.to_owned() 将简单地返回 c 的克隆,因此不会影响值的结构。 - sebpuetz

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接