1

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?

nbro
  • 15,395
  • 32
  • 113
  • 196
Adam
  • 1,684
  • 1
  • 19
  • 39

2 Answers2

3

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.

Community
  • 1
  • 1
fjh
  • 12,121
  • 4
  • 46
  • 46
  • 1
    Ok, I understand the design. However, is there any help with the design of the structs that needs to reference to itself? How can I redesign my struct to fulfill this need? – Adam Aug 03 '15 at 19:14
-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.

A.B.
  • 15,364
  • 3
  • 61
  • 64
  • 1
    I'm not asking for spliting the strings, and I think there're cases that you'll need to reference yourself in the struct. – Adam Aug 04 '15 at 04:23