Initialize a structure field using another field of the same structure

Below I have a struct SplitByChars .

 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: I cannot use self here! } } } 

I am trying to implement a static function new for it. In particular, I would like to return an instance of SplitByChars whose chars_iter field chars_iter initialized using the previously initialized string field of the same instance. For this, I'm currently trying to access a single field using self.string , but I am getting an error.

How can i do this?

0
source share
2 answers

How can i do this?

You can not. If I do not understand your question, this is the same problem as this one . Structures usually cannot have references to themselves.

+1
source

I think you make things too complicated. Dividing a string into specific characters can be done using:

 let s: String = "Tiger in the snow".into(); for e in s.split(|c| c == 'e') { println!("{}", e); } 

Output:

 Tig r in th snow 

There are several options for the split function to meet different needs.

-1
source

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


All Articles