戻り値とスコープ
fn main() {
let s1 = gives_ownership();
print!("{}", s1); // hello
let s2 = String::from("hello");
let s3 = takes_and_gives_back(s2);
print!("{}", s3); // hello
// error[E0382]: borrow of moved value: `s2`
print!("{}", s2);
}
fn gives_ownership() -> String {
let some_string = String::from("hello");
some_string
}
fn takes_and_gives_back(a_string: String) -> String {
a_string
}
fn main() {
let s1 = String::from("hello");
let (s2, len) = calculate_length(s1);
// The length of 'hello' is 5.
println!("The length of '{}' is {}.", s2, len);
}
fn calculate_length(s: String) -> (String, usize) {
let length = s.len();
(s, length)
}
fn main() {
let s1 = String::from("hello");
// error[E0308]: mismatched types
let len = calculate_length(s1);
println!("The length of '{}' is {}.", s1, len);
}
fn calculate_length(s: &String) -> usize {
s.len()
}
fn main() {
let s1 = String::from("hello");
let len = calculate_length(&s1);
// The length of 'hello' is 5.
println!("The length of '{}' is {}.", s1, len);
}
fn calculate_length(s: &String) -> usize {
s.len()
}