impl Parse {
fn new(source: String) -> Self {
Self {
pos: 0,
input: source,
}
}
fn parse_nodes(&mut self) -> usize {
for (index, char) in self.next_ele() {
self.pos += 1
}
self.pos
}
fn next_ele(&self) -> CharIndices {
self.input.char_indices()
}
}
let mut v = Parse::new("<div><div></div></div>".to_string());
let c = v.parse_nodes();
println!("{}",c)
error: cannot assign to self.pos
because it is borrowed
How can I make C normal print?
The error is due to the fact that next_ele
puts a borrow of self
into its return value - compiler doesn't try to check what it really needs to borrow, all that is checked is the signature. You can't mutate self
while holding a borrow to it, this is not connected to printing.
use std::str::CharIndices;
struct Parse {
pos: usize,
input: String,
}
impl Parse {
fn new(source: String) -> Self {
Self {
pos: 0,
input: source,
}
}
fn parse_nodes(&mut self) -> usize {
for _ in 0..self.next_ele().count() {
self.pos += 1;
}
self.pos
}
fn next_ele(&self) -> CharIndices {
self.input.char_indices()
}
}
fn main() {
let mut v = Parse::new("<div><div></div></div>".to_string());
let c = v.parse_nodes();
println!("{}",c);
}
Playground
But there is a little trick here.
Couldn't this be written to avoid the loop in the first place?
fn parse_nodes(&mut self) -> usize {
self.pos += self.next_ele().count();
self.pos
}
if there is no other work in the loop, you're right
I don't understand ,could you explain ?
Why are index
and char
involved here? This is what I mean when I talk about some extra work in the loop.
i got it .
index and char be invoked in other place,
there is a simplify code
1 Like
system
Closed
May 24, 2022, 5:52am
9
This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.