fn main() {
let mut s1 = String::from("hello");
let (s1, len) = calculate_length(s1);
s1.push_str(" world"); // Error s1 is immutable
println!("The length of '{}' is {}.", s1, len);
}
fn calculate_length(s: String) -> (String, usize) {
let length = s.len(); // len() returns the length of a String
(s, length)
}
how can I point to already defined s1 without having to create another mutable variable like this
let (mut s1, len) = calculate_length(s1);
Considered answer
Why are you passing String
to calculate_length
instead of just &str
?
Direct answer
Like this:
fn main() {
let mut s1 = String::from("hello");
let len;
(s1, len) = calculate_length(s1);
s1.push_str(" world"); // Error s1 is immutable
println!("The length of '{}' is {}.", s1, len);
}
fn calculate_length(s: String) -> (String, usize) {
let length = s.len(); // len() returns the length of a String
(s, length)
}
https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=c0652fa2e158f4c3e00685b7e5841113
3 Likes
FYI, the code in the question seems to be adapted from the last example on this page of the Rust book .
It's used as a motivation for introducing the concept of borrowing on the next page. String slices and the suggestion to use &str
in place of &String
for function parameters come yet another page later.
2 Likes
system
Closed
October 3, 2022, 3:46am
4
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.