Function need to | code | |
---|---|---|
update internal variable | update original variable | |
No | No |
fn example(some_int: i32) {
println!("Value of some_int is {}", some_int);
}
fn main() {
let x = 1;
example(x);
// x still in scope and equal to 1
println!("x={}", x);
} |
Yes | No |
fn example(mut some_int: i32) {
some_int += 99;
// value of some_int is updated to 100
println!("Value is updated to {}", some_int);
}
fn main() {
let x = 1;
example(x);
// x still in scope and equal to 1
println!("x={}", x);
} |
Yes | Yes |
fn example(mut some_int: i32) -> i32 {
some_int += 99;
println!("Value is updated to {}", some_int);
some_int
}
fn main() {
let mut x = 1;
x = example(x);
// x still in scope was updated by function to 100
println!("Value is updated to {}", x);
} |
Function need to | code | |
---|---|---|
update internal variable | update original variable | |
No | No |
fn example(some_int: &i32) {
println!("Value is {}", some_int);
}
fn main() {
let x = 1;
example(&x);
// x still in scope and equal to 1
println!("x={}", x);
} |
Yes | Yes |
fn example(some_int: &mut i32) {
*some_int += 99;
println!("Value is updated to {}", some_int);
}
fn main() {
let mut x = 1;
example(&mut x);
// x still in scope and was updated to 100
println!("x={}", x);
} |
Function need to | code | |
---|---|---|
update internal variable | update original variable | |
No | No |
fn example(some_str: String) {
println!("Value is {}", some_str);
}
fn main() {
let s = String::from("Hello");
example(s);
// s was borrowed by example, it is not in scope
} |
Yes | No |
fn example(mut some_str: String) {
some_str.push_str(" world");
println!("Value is {}", some_str);
}
fn main() {
let s = String::from("Hello");
example(s);
// s was borrowed by example, it is not in scope
} |
Yes | Yes |
fn example(mut some_str: String) -> String{
some_str.push_str(" world");
println!("Value is {}", some_str);
some_str
}
fn main() {
let mut s = String::from("Hello");
s = example(s);
// s was borrowed and returned by example, it is back in scope
println!("updated value of s is {}", s);
} |
Function need to | code | |
---|---|---|
update internal variable | update original variable | |
No | No |
fn example(some_str: &String) {
println!("Value is {}", some_str);
}
fn main() {
let s = String::from("Hello");
example(&s);
// s is still in scope
println!("s={}", s);
} |
Yes | Yes |
fn example(some_str: &mut String){
some_str.push_str(" world");
println!("Value is {}", some_str);
}
fn main() {
let mut s = String::from("Hello");
example(&mut s);
// s is still in scope and was updated by example to "hello world"
println!("updated value of s is {}", s);
} |