I'm very new to Rust, so this most probably a stupid question to ask.
I've couple of questions.
I've these two functions:
fn modifier2(mut ptr: Box<String>) -> Box<String> {
println!("In modifier2...");
println!("Ptr points to {:p}, and value is {}", ptr, *ptr);
*ptr = ptr.to_uppercase();
println!("Exit modifier2...");
ptr
}
fn modifier3(ptr: &mut Box<String>) {
println!("In modifier3...");
println!("Ptr points to {:p}, and value is {}", ptr, *ptr);
println!("Ptr points to {:p}, and value is {}", *ptr, **ptr);
**ptr = "another".to_uppercase();
//**ptr = **ptr.to_uppercase(); //error[E0614]: type `str` cannot be dereferenced
println!("Exit modifier3...");
}
And I'm calling them like this:
let mut answer = Box::new("Hello World".to_string());
answer = modifier2(answer);
println!("called modifier2(): {} length: {}", answer, answer.len());
let mut answer = Box::new("Hello World".to_string());
modifier3(&mut answer);
println!("called modifier3(): {} length: {}", answer, answer.len());
This results the following, which looks fine to me:
In modifier2...
Ptr points to 0x2145fa1d990, and value is Hello World
Exit modifier2...
called modifier2(): HELLO WORLD length: 11
In modifier3...
Ptr points to 0x50426ffb60, and value is Hello World
Ptr points to 0x2145fa1dc50, and value is Hello World
Exit modifier3...
called modifier3(): ANOTHER length: 7
I've two questions:
1) In fn modifier2(mut ptr: Box) -> Box , what is the significance of making the ptr as mute? How it differs from fn modifier2(ptr: mut Box) -> Box ?
2) In the commented line in fn modifier3, i.e., **ptr = **ptr.to_uppercase();, results in an error "error[E0614]: type str
cannot be dereferenced", while I can do the same uppercase() in fn modifier2?
Thanks for any help.
EDIT: If I change modifier3() like this:
fn modifier3(&mut ptr: &mut Box<String>) {
println!("In modifier3...");
println!("Ptr points to {:p}, and *PTR points to {}, and value is {}", ptr, *ptr, **ptr);
*ptr = "another".to_uppercase(); //or **ptr = *"another".to_uppercase();
println!("Exit modifier3...");
}
It gives the following errors:
error[E0277]: the size for values of type `str` cannot be known at compilation time
--> src\main.rs:99:5
|
99 | println!("Ptr points to {:p}, and *PTR points to {}, and value is {}", ptr, *ptr, **ptr);
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time
A little confused here with the usage of &mut ptr.
Thanks.