I have the following code that takes usize
in an enum and I wanted to iterate on that usize
. When I pass usize
directly to the for loop, I get compilation error "expected Integer but found &usize
. However, when I clone the usize, the for loop works.
Up on looking the documentation, the clone()
method is expected to return usize
as well. Is this code working because the clone method gives ownership to the for loop but the original size
variable is passed by reference ?
pub enum Command {
Uppercase,
Trim,
Append(usize),
}
fn some_fun(command: Command, string: String) {
match command {
Command::Append(size)=> {
let mut str = string.clone();
let s = size.clone();
for i in 0..s {
str.push_str("bar");
}
}
}
CodePudding user response:
For a range expression, you need values, not references. The type of size
ends up being a reference due to "match ergonomics". You don't show the expression you are matching on, but it's likely the type of your match value is &Command
. If you add an &
at the beginning of your pattern, i.e. &Command::Append(size)
, the type of size
will be usize
, and iterating over 0..size
should work fine.
CodePudding user response:
Yes. Iterating over ranges requires values, not references. However, since usize
is Copy
, it is better to just dereference: for i in 0..*size
.