Skip to navigation
In rust to give a function a pointer from a variable outer scope and change it
03.07.25
```rust fn print_value(val: &i32) { println!("The value is: {}", val); } fn main() { let x = 42; print_value(&x); } ``` &x is a reference (a kind of pointer) to x, which is in the outer scope of print_value. The function signature fn print_value(val: &i32) means it accepts a reference to an i32 Example: Passing a Mutable Reference If you want the function to modify the variable: ```rust fn add_one(val: &mut i32) { *val += 1; } fn main() { let mut x = 42; add_one(&mut x); println!("x after: {}", x); // Output: x after: 43 } &mut x gives a mutable reference to x. The function receives val: &mut i32 and can modify it using *val. ```
https://doc.rust-lang.org/book/ch04-02-references-and-borrowing.html
Reply
Anonymous
Information Epoch 1752386812
Save trees.
Home
Notebook
Contact us