gpt4 book ai didi

pointers - 如何在不一直取消引用指针的情况下修复错误 "cannot move out of dereference"?

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

我刚刚阅读完 rust-lang.org 上的生命周期指南并尝试实现该示例(但使用通用枚举来增加一点复杂性)。

enum PositionInfo<T> {
Position(T, T),
}

enum ShapeInfo<T> {
RectInfo(T, T),
CircleInfo(T),
}

enum GeometricObject<T>{
Circle(PositionInfo<T>, ShapeInfo<T>),
Rectangle(PositionInfo<T>, ShapeInfo<T>),
}

impl<T:Num> GeometricObject<T>{
fn get_area(&self) -> Option<T> {
match *self {
Circle(_, CircleInfo(r)) => Some(r * r),
Rectangle(_, RectInfo(w, h)) => Some(w * h),
_ => None,
}
}
}

当我尝试编译代码时,出现以下错误

enum_tut.rs:28:9: 28:14 error: cannot move out of dereference of `&`-pointer
enum_tut.rs:28 match *self {
^~~~~
enum_tut.rs:29:29: 29:30 note: attempting to move value to here (to prevent the move, use `ref r` or `ref mut r` to capture value by reference)
enum_tut.rs:29 Circle(_, CircleInfo(r)) => Some(r * r),
^
enum_tut.rs:30:30: 30:31 note: and here (use `ref w` or `ref mut w`)
enum_tut.rs:30 Rectangle(_, RectInfo(w, h)) => Some(w * h),
^
enum_tut.rs:30:33: 30:34 note: and here (use `ref h` or `ref mut h`)
enum_tut.rs:30 Rectangle(_, RectInfo(w, h)) => Some(w * h),
^
error: aborting due to previous error

看报错信息,我重写了如下实现,编译没有报错。

这段代码看起来很困惑;在我明确要求它的引用后,我必须取消引用 4 个指针。

有没有什么办法可以把代码写的更干净一些?

impl<T:Num> GeometricObject<T>{
fn get_area(&self) -> Option<T> {
match *self {
Circle(_, CircleInfo(ref r)) => Some(*r * *r),
Rectangle(_, RectInfo(ref w, ref h)) => Some(*w * *h),
_ => None,
}
}
}

最佳答案

问题是您的代码不知道复制 T 是安全的,因为您没有告诉它。唯一安全的事情是引用对象并取消引用它们。否则,您可能会导致资源泄漏或破坏安全保证。

试试这个(围栏现在不工作,所以我无法验证...):

使用rust 1.0

impl<T> GeometricObject<T>
where T: Copy + std::ops::Mul<Output=T>
{
fn get_area(&self) -> Option<T> {
use GeometricObject::*;
use ShapeInfo::*;

match *self {
Circle(_, CircleInfo(r)) => Some(r * r),
Rectangle(_, RectInfo(w, h)) => Some(w * h),
_ => None,
}
}
}

原创

impl<T:Num+Copy> GeometricObject<T>{
fn get_area(&self) -> Option<T> {
match *self {
Circle(_, CircleInfo(r)) => Some(r * r),
Rectangle(_, RectInfo(w, h)) => Some(w * h),
_ => None,
}
}
}

关于pointers - 如何在不一直取消引用指针的情况下修复错误 "cannot move out of dereference"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27626167/

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