Initialize a field of a struct using another field

2019-01-29 10:48发布

问题:

This question already has an answer here:

  • How to initialize struct fields which reference each other 1 answer

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 new static function for it. In particular, I would like to return a SplitByChars instance whose chars_iter field is initialized using the previously initialized string field of the same instance. To do that, I am currently trying to access the same field using self.string, but I am getting an error.

How can I do it?

回答1:

How can I do it?

You can't. Unless I misunderstand your question, this is the same problem as this one. Structs generally cannot have references into themselves.



回答2:

I think you're making things overly complicated. Splitting a string at specific chars can be done with:

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 variations of the split function to suit various needs.



标签: rust