Initialize a field of a struct using another field

2019-01-29 10:25发布

This question already has an answer here:

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?

标签: rust
2条回答
Lonely孤独者°
2楼-- · 2019-01-29 11:02

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.

查看更多
男人必须洒脱
3楼-- · 2019-01-29 11:07

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.

查看更多
登录 后发表回答