简体   繁体   English

如何在不需要 Copy 特征的情况下返回引用?

[英]How to return a reference without requiring Copy trait?

The Rust Programming Language has an example function that returns the largest element of a slice . Rust 编程语言一个示例 function 返回切片的最大元素 It is mentioned that instead of returning the value, it should be possible to return a reference to that value which would allow us to use this function with types that do not implement the Copy trait.有人提到,应该可以返回对该值的引用,而不是返回该值,这将允许我们将此 function 与不实现Copy特征的类型一起使用。

The initial function that returns the value looks like this:返回值的初始 function 如下所示:

fn largest<T>(list: &[T]) -> T
where
    T: PartialOrd + Copy,
{
    let mut largest = list[0];

    for &item in list {
        if item > largest {
            largest = item;
        }
    }
    largest
}

I've been trying to modify it for a while now in order to return a pointer to that value instead of the value itself.我一直在尝试修改它一段时间,以便返回指向该值的指针而不是值本身。 I'm thinking this could also be implemented using the index, but I was wondering if there was no other way to proceed like in this attempt:我认为这也可以使用索引来实现,但我想知道是否没有其他方法可以像这次尝试那样进行:

fn largest<'a, T: 'a>(list: &'a [T]) -> &'a T
where
    &'a T: PartialOrd,
{
    let mut largest = &list[0];

    for &item in list {
        if item > *largest {
            largest = &item;
        }
    }
    largest
}

This code does not compile and the compiler keeps panicking since I'm obviously missing something.这段代码无法编译,编译器不断恐慌,因为我显然遗漏了一些东西。 In this instance it refuses to apply the binary operation '>', even though I'm "following" so to speak the the pointer that is largest to the value it represents:在这种情况下,它拒绝应用二进制操作'>',即使我“跟随”可以说最大的指针,它代表的值:

error[E0369]: binary operation `>` cannot be applied to type `T`
 --> src/lib.rs:8:17
  |
8 |         if item > *largest {
  |            ---- ^ -------- T
  |            |
  |            T
  |
help: consider further restricting type parameter `T`
  |
3 |     &'a T: PartialOrd, T: std::cmp::PartialOrd
  |                      ^^^^^^^^^^^^^^^^^^^^^^^^^

I'd be grateful if someone had a hint as to what direction I should poke in order to get this approach to work, if possible at all?如果有人暗示我应该朝哪个方向努力以使这种方法发挥作用,我将不胜感激,如果可能的话?

While not being much of a surprise, this turned out to be a silly mistake: The item in the iteration didn't need to be a reference, and largest most certainly didn't need to be dereferenced.虽然不足为奇,但事实证明这是一个愚蠢的错误:迭代中的item不需要是引用, largest肯定不需要取消引用。 Here's the fixed version of that code:这是该代码的固定版本:

fn largest<'a, T: 'a>(list: &'a [T]) -> &'a T
where
    &'a T: PartialOrd,
{
    let mut largest = &list[0];

    for item in list {
        if item > largest {
            largest = &item;
        }
    }
    largest
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM