How to create a structure when I need to refer to myself

My previous question tells me that rust cannot refer to itself in a structure.

using self in the new constructor

So my question will be: how to create a structure when I need to refer to myself?

We could take this structure as an example:

struct SplitByChars<'a> { seperator: &'a Seperator, string: String, chars_iter: std::str::Chars<'a>, } impl<'a> SplitByChars<'a> { fn new<S>(seperator: &'a Seperator, string: S) -> SplitByChars where S: Into<String> { SplitByChars { seperator: seperator, string: string.into(), chars_iter: self.string.chars(), // error here: I cannot use self (of course, static method) } } } 

I used chars_iter to provide an chars_iter line split interface.

(This is just an example, so I would like to learn about the more general idea of โ€‹โ€‹designing a structure, and not specifically in this case of splitting. Moreover, std is not broken.)

thanks in advance!

+4
source share
2 answers

You can not. Rust iterators are not intended to be used in this way. Reorder things so that you don't need to store the string inside the iterator. It should have only a link.

+1
source

As long as the field cannot refer to another field within the structure, you can usually achieve what you need while moving . It works using one field as data and another field as Option , containing some structure that takes this data by value (and realizing some features of your interest).

You can find an example in this answer that implements the itetaror adapter, where the data was a HashMap , and Option contains an IntoIter map. During the iteration, when access to the map is no longer needed, it moved to IntoIter using std::mem::replace .

However, in your particular case there is no method in std that create a Chars iterator by consuming String (i.e. using self as an argument). You will have to implement it yourself.

+1
source

Source: https://habr.com/ru/post/1235500/


All Articles