Implementing Index trait to return a value that is not a reference

前端 未结 2 1152
猫巷女王i
猫巷女王i 2020-11-29 13:36

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

相关标签:
2条回答
  • 2020-11-29 13:58

    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.

    0 讨论(0)
  • 2020-11-29 13:59

    This use case does not match the intuition for Index. When I see myStruct[3], my intuition is that, just as for arrays, I'm getting a pointer to some already-initialized data. The interface for Index corroborates this intuition.

    I can see two things that you might potentially be trying to achieve:

    1. Getting nice indexing syntax for your datastructure.

    In this case I would recommend against the premise of implementing Index and just provide a method that returns a f64 instead of an &f64 like so.

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

    You don't get the operators, which is good because somebody reading [] would be mislead into thinking they were getting a pointer. But you do get the functionality you want. Depending on your use cases you may want to rename this method.

    1. Passing MyStruct to a parameter with Index bounds.

    This is trickier with good reason. Index expects the data to be there before it asks for it. You can't generate and return it because index returns f64, and you can't generate it in the datastructure and return a pointer because it doesn't take a &mut self. You'd have to populate these values before the call to index. Some redesign would be in order, and the direction of that redesign would depend on the larger context of your problem.

    0 讨论(0)
提交回复
热议问题