Beginner question : passing a mut reference variable to function for reuse

Using this crate : ratelimit = "0.4.4".
Wanted to give a playground link, but this crate is not supported

In this code, want to pass rateLimiter variable made in main function and pass it down to fetch for reusing multiple times.

I get errors in fetch like:
"expected &mut Limiter, found struct LimiterrustcE0308"

I did change the signature to : &mut . But it didn't help.

fn createRateLimiter()->Limiter{
    let mut rate_limit = ratelimit::Builder::new()
    .capacity(1) //number of tokens the bucket will hold
    .quantum(1) //add one token per interval
    .interval(std::time::Duration::from_secs(10)) //add quantum tokens every 1 second
    .build();

    rate_limit
}

fn main(){
    let rate_limiter = createRateLimiter();

    for n in 1..=5 {
       fetch(&rate_limiter).await;
    } 
}

fn fetch(rate_limiter:&mut Limiter){
  rate_limiter.wait()
}

The problem here is basically that your fetch function expected a mutable reference, but you only gave it an immutable reference.

The place where the fetch function is called, using &argument only passes the immutable reference to the function. If you call it with fetch(&mut argument), the can itself will work. After that, you will also have to make the variable itself mutable:

    let mut rate_limiter = createRateLimiter();

    for n in 1..=5 {
       fetch(&mut rate_limiter).await;
    } 

See this example in the rust book for a more in-depth expanation :slight_smile:

Did this help you?

1 Like

Ah thank you !
I did try that. But I'm using Rust Analyzer in VSCode. And I was getting error messages using the static analyzer only.

1 Like

You'll also need to declare the variable as mutable.

fn main(){
    let rate_limiter = createRateLimiter();

    for n in 1..=5 {
       fetch(&rate_limiter).await;
    } 
}

fn fetch(rate_limiter:&mut Limiter){
  rate_limiter.wait()
}

Should be

fn main(){
    let mut rate_limiter = createRateLimiter();
        ^^^
    for n in 1..=5 {
        fetch(&mut rate_limiter).await;
    }          ^^^
}

fn fetch(rate_limiter:&mut Limiter){
  rate_limiter.wait()
}
1 Like