struct StringIter {
current: Option<usize>,
list: Vec<Vec<u8>>,
len: usize,
}
impl StringIter {
fn iter(&mut self) {
for i in 0..self.len {
let current = self.current.unwrap();
if i != current {
self.list[i].extend_from_slice(&self.list[current].as_slice());
}
}
}
}
fn main() {}
or simply version:
let mut s = vec![vec![1],vec![2]];
s[0].extend_from_slice(s[1].as_slice());
The compiler says cannot borrow self.list as immutable, actually I know the reason, but I can't find a way to fix this.
You can obtain mutable access to multiple elements by using slice patterns, like this:
let mut s = vec![vec![1],vec![2]];
match &mut *s {
[first, second, ..] => {
first.extend_from_slice(second.as_slice());
}
_ => {} // handle index out of bounds
}
Oh, that's amazing, thanks for your answer, it really works for the simply version.
But the code is like this, is there an elagant way to fix it? By the way, I don't know if slice patterns work for the unknown index.
impl StringIter {
fn iter(&mut self) {
for i in 0..self.len {
let current = self.current.unwrap();
if i != current {
self.list[i].extend_from_slice(self.value());
}
}
}
fn value(&self)->&[u8]{
// do something
let current = self.current.unwrap();
&self.list[current]
}
}