实现Index trait以返回不是引用的值 [英] Implementing Index trait to return a value that is not a reference

查看:111
本文介绍了实现Index trait以返回不是引用的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的结构,我想实现索引,但作为Rust的新手,我在借用检查器方面遇到了一些麻烦。我的结构非常简单,我想让它存储一个开始和步骤值,然后当用 usize 索引时,它应该返回 start + idx * step

I have a simple struct that I would like to implement Index for, but as a newcomer to Rust I'm having a number of troubles with the borrow checker. My struct is pretty simple, I'd like to have it store a start and step value, then when indexed by a usize it should return start + idx * step:

pub struct MyStruct {
    pub start: f64,
    pub step: f64,
}

我的直觉是我只是能够接受索引的签名并插入我的类型:

My intuition is that I'd simply be able to take the signature of Index and plug in my types:

impl Index<usize> for MyStruct {
    type Output = f64;

    fn index(&self, idx: usize) -> &f64 {
        self.start + (idx as f64) * self.step
    }
}

这会给出错误不匹配类型期望类型&f64,找到类型f64 。作为尚未完全理解Rust的类型系统如何工作的人,我尝试在表达式上简单地拍打&

This gives the error mismatched types saying expected type &f64, found type f64. As someone who has yet to fully understand how Rust's type system works, I tried simply slapping & on the expression:

fn index(&self, idx: usize) -> &f64 {
    &(self.start + (idx as f64) * self.step)
}

这现在告诉我借来的值不够长,所以也许它需要一个生命周期变量?

This now tells me that the borrowed value does not live long enough, so maybe it needs a lifetime variable?

fn index<'a>(&self, idx: usize) -> &'a f64 {
    &(self.start + (idx as f64) * self.step)
}

错误是相同的,但现在注释给出 lifetime'a 而不是生命周期#1 ,所以我猜这不是必要的,但在这一点上我觉得我被卡住了。我很困惑,大多数语言的这种简单练习在Rust中变得如此难以实现,因为我想要做的就是从恰好位于引用后面的函数返回一个计算。我应该如何为一个简单的结构实现索引,其中值是按需计算的?

The error is the same, but the note now gives lifetime 'a instead of lifetime #1, so I guess that's not necessary, but at this point I feel like I'm stuck. I'm confused that such a simple exercise for most languages has become so difficult to implement in Rust, since all I want to do is return a computation from a function that happens to be behind a reference. How should I go about implementing Index for a simple structure where the value is calculated on demand?

推荐答案

索引特征是为了将一个借来的指针返回给 self 的成员(例如 Vec 中的项目。来自索引特征的索引方法的签名使得实现它以实现您描述的行为是不切实际的,如你必须在 self 中存储 index 返回的每个值,并确保指针在<$之前保持有效c $ c> MyStruct 被删除。

The Index trait is meant to return a borrowed pointer to a member of self (e.g. an item in a Vec). The signature of the index method from the Index trait makes it impractical to implement it to have the behavior you described, as you'd have to store every value returned by index in self and ensure that the pointers remain valid until the MyStruct is dropped.

这篇关于实现Index trait以返回不是引用的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆