CodeBlanks Logo Icon CodeBlanks

References and functions

Pass references into functions and return them.

References and functions

A function signature states clearly what will be done with the value:

  • fn f(v: Vec<i32>) — takes ownership (consumes it).
  • fn f(v: &Vec<i32>) or &[i32] — only reads.
  • fn f(v: &mut Vec<i32>) — changes it in place.
fn toplam(v: &[i32]) -> i32 { v.iter().sum() }
fn ikiye_katla(v: &mut Vec<i32>) {
    for x in v.iter_mut() { *x *= 2; }
}

iter and iter_mut

iter() gives elements as &T, iter_mut() as &mut T. The second is used to change elements in place, and each element is dereferenced with *:

let mut fiyatlar = vec![10.0, 20.0];
for f in fiyatlar.iter_mut() {
    *f *= 1.2;
}
println!("{:?}", fiyatlar);   // [12.0, 24.0]

Writing for x in &mut v is the same as v.iter_mut().

Practice Read and modify

Write the functions fn toplam(v: &[i32]) -> i32 and fn ikiye_katla(v: &mut Vec<i32>). For let mut v = vec![1, 2, 3];, call ikiye_katla(&mut v) first, then toplam(&v), and print v and the sum.

Starter code

main.rs
fn main() {
    // buraya yaz
}

Sample solution

main.rs
fn toplam(v: &[i32]) -> i32 {
    v.iter().sum()
}

fn ikiye_katla(v: &mut Vec<i32>) {
    for x in v.iter_mut() {
        *x *= 2;
    }
}

fn main() {
    let mut v = vec![1, 2, 3];
    ikiye_katla(&mut v);
    let t = toplam(&v);
    println!("{:?} {}", v, t);
}

Expected output

[2, 4, 6] 12

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 For a function that only reads a vector, which parameter is most flexible?

  • &mut Vec<i32>
  • &Vec<i32>
  • &[i32] Correct answer
  • Vec<i32>

Explanation: A slice reference accepts &Vec<i32>, arrays and sub-slices; &Vec accepts only a vector.

2 Change in place

Question
for x in v.____() {
    *x += 1;
}
Answer
for x in v.iter_mut() {
    *x += 1;
}

Explanation: iter_mut gives mutable references to the elements.

3 Signature and intent

Term Meaning
v: Vec<T> Consumes
v: &[T] Reads
v: &mut Vec<T> Modifies
v.iter_mut() &mut T elements

All lessons in Beginner