gpt4 book ai didi

Rust 解构结构引用与解构结构

转载 作者:行者123 更新时间:2023-12-03 11:27:40 26 4
gpt4 key购买 nike

以下代码有效

#[derive(Debug)]
struct Rectangle {
width: u32,
height: u32
}

fn area(shape: &Rectangle) -> u32 {
let Rectangle{width, height} = shape;
width * height
}

fn main() {
let rec1 = Rectangle {width: 5, height: 10};
println!("Area {}", area(&rec1));
println!("Rec {:?}", rec1);
}

但是用解引用引用 *&Shape 替换对 struct &Shape 的引用也可以(例如 let Rectangle{width, height} = shape; --> let矩形{width, height} = *shape;).

我不知道为什么两者都有效,破坏时是否有一些隐式取消引用?我虽然 &Shape 引用只指向 Shape 在内存中的位置,而 *&ShapeShape 本身。 widthheightstruct Rectangle 的属性,而不是引用 &Rectangle 的属性。

最佳答案

I have no idea why both work, is there some implicit dereferencing when destructing?

这是 2018 版 match ergonomics 的一个(方便但令人困惑的)结果: 当匹配引用类型时,编译器会隐式添加引用并取消引用,所以事情是正确的。

area 中发生的情况是 widthheight&u32 而不是 u32,编译器有效地将您的代码解释为:

let &Rectangle{ ref width, ref height } = shape;

如果你没有使用像 rust-analyzer 这样可以直接在你的编辑器中显示这些信息的工具,一个常见的技巧是编写如下内容:

let x: () = var

编译错误会告诉你var的类型是什么(除非是())。

I though &Shape reference only points to where Shape is in memory, whereas *&Shape is Shape itself.

确实如此,但是在 模式 的上下文中,这并不一定意味着结构被移动。这里因为 Rectangle 的字段都是 Copy 编译器可以解构“拥有”结构而不需要移动它,它可以只复制字段。这本质上是一个简单的属性访问会做的事情(shape.widthu32)。

关于Rust 解构结构引用与解构结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66363243/

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