Passing a function as parameter: as reference or as value?

⚓ Rust    📅 2025-06-23    👤 surdeus    👁️ 5      

surdeus

Warning

This post was published 50 days ago. The information described in this article may have changed.

What is the difference if I define a function parameter as reference or as value (other that the parameter is moved)? Is there a performance difference?

pub fn calculate(
    data: &[SomeStruct],
    config: &Config,
    f_result_analyzer: &dyn Fn(&ResultBatch) -> i32,
) {...}

In this case I cannot remove the & before dyn and must pass the function as reference, as otherwise the compiler complains the size cannot be known at compile time. This makes sense, as anyhow only the address of the function is passed (or not?).

But I can rewrite the definition to

pub fn calculate<F>(
  data: &[SomeStruct],
  config: &Config, 
  f_result_analyzer: &F) 
where
    F: Fn(&ResultBatch) -> i32,
{...}

and also as value (note missing & before F):

pub fn calculate<F>(
  data: &[SomeStruct],
  config: &Config, 
  f_result_analyzer: F) 
where
    F: Fn(&ResultBatch) -> i32,
{...}

So I wonder: Is there any difference between the last two definitions?

2 posts - 2 participants

Read full topic

🏷️ rust_feed