Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is using `ref` in a function argument the same as automatically taking a reference?

Tags:

rust

Rust tutorials often advocate passing an argument by reference:

fn my_func(x: &Something)

This makes it necessary to explicitly take a reference of the value at the call site:

my_func(&my_value).

It is possible to use the ref keyword usually used in pattern matching:

fn my_func(ref x: Something)

I can call this by doing

my_func(my_value)

Memory-wise, does this work like I expect or does it copy my_value on the stack before calling my_func and then get a reference to the copy?

like image 929
Yves Parès Avatar asked Feb 05 '14 10:02

Yves Parès


People also ask

When to use ref keyword in c#?

When used in a method's parameter list, the ref keyword indicates that an argument is passed by reference, not by value. The ref keyword makes the formal parameter an alias for the argument, which must be a variable. In other words, any operation on the parameter is made on the argument.

What does REF mean C#?

The ref keyword in C# is used for passing or returning references of values to or from Methods. Basically, it means that any change made to a value that is passed by reference will reflect this change since you are modifying the value at the address and not just the value.

What is ref in C# with example?

C# includes ref and out are keywords, which help us to pass the value type variables to another function by the reference. The following example demonstrates passing a value type variable by reference using the ref keyword. Example: Passing Value Type by Reference.


1 Answers

The value is copied, and the copy is then referenced.

fn f(ref mut x: i32) {
    *x = 12;
}

fn main() {
    let mut x = 42;
    f(x);
    println!("{}", x);
}

Output: 42

like image 181
A.B. Avatar answered Sep 19 '22 19:09

A.B.