Is it possible to replace all function arguments with just one struct argument?

⚓ Rust    📅 2025-09-29    👤 surdeus    👁️ 12      

surdeus

Warning

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

I have function with > 10 arguments, like this:

fn f(a1: &T1, a2: &T2, ... a6: &T6, a7: &mut T7, ... a11: &mut T11) {...}

and I call it like this:

fn call_f(a1: &T1, a2: &T2, ... a6: &T6, a7: &mut T7, ... a11: &mut T11)
{
   {
      let tmp = ...;
      let a2 = &tmp;
      f(a1, a2, ...);
   }
   f(a1, a2, ...);
}

all works fine, but I need to call f three more times.

So I want to refactor it like this:

struct Context<'a> {
  a1: &'a T1,
  a2: &'a T2,
...
}

In my imagination it would be as simple as:

fn call_f(a1: &T1, a2: &T2, ... a6: &T6, a7: &mut T7, ... a11: &mut T11)
{
  let mut ctx = Context {a1, a2, ... };
   {
      let tmp = ...;
      ctx.a2 = &tmp;
      f(&mut ctx);
   }
   f(&mut ctx);
}

But I suppose you see the problem, a2 should has variable lifetime to make it work. Any way to solve this problem, to make possible to change a2 field on the fly?

2 posts - 2 participants

Read full topic

🏷️ Rust_feed