Save string and CharIndices in the same struct?


#1

How can I save a string and the CharIndices returned by calling the char_indices() method on this string in the same struct? I other words how do I make the following work?

use std::str::CharIndices;

struct MyStruct<'a> {
    input: String,
    chars: CharIndices<'a>,
}

impl<'a> MyStruct<'a> {
    fn new(inp: String) -> MyStruct<'a> {
        MyStruct{ input: inp, chars: inp.char_indices() }
    }
}

fn main() {
    let s = MyStruct::new("test".into());
}

Playpen


#2

You can’t (without shenanigans) have a thing and a reference to that thing (which CharIndices contains) in the same struct: it would make the struct unmoveable because the pointers inside CharIndices would become invalid when moved.

You can do it with a Vec: https://is.gd/gSDzYo


#3

You can also use a string slice instead, if you don’t need to mutate it. You wouldn’t be able to mutate it anyway.

use std::str::CharIndices;

struct MyStruct<'a> {
    input: &'a str,
    chars: CharIndices<'a>,
}

impl<'a> MyStruct<'a> {
    fn new(inp: &'a str) -> MyStruct<'a> {
        MyStruct{ input: inp, chars: inp.char_indices() }
    }
}

fn main() {
    let s = MyStruct::new("test");
}