stm32-rs / stm32f1xx-hal

A Rust embedded-hal HAL impl for the STM32F1 family based on japarics stm32f103xx-hal

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Moving out of mutable reference for Parts

mryndzionek opened this issue · comments

Hello,

I would like to do GPIO initialization in a separate function, mostly for clarity/convenience.
I have a function like:

fn init(gpioa: &mut Parts)  {
    gpioa.pa8.into_alternate_push_pull(&mut gpioa.crh);
    .
    .
    .
}

This doesn't work:

error[E0507]: cannot move out of `gpioa.pa8` which is behind a mutable reference

Is there a solution to this? I think having an option of doing GPIO initialization in separate functions passing around &mut Parts is a useful thing.

Thata's not possible to do, because we use the ownership system to ensure that each pin (and hardware resource in general) is only used once. So .into_alternate_push_pull takes ownership over pa8. It's a bit of a tradeoff between ease of writing and safety, but we choose to lean towards the safety side to avoid having to do debugging if 2 pieces of code accidentally try to use the same hardware.

In your case, you may be able to take ownership over Parts and return the pins you're interested in, i.e.

fn init_gpioa(gpioa: Parts) -> Pa8<Alternate<PushPull>> { // This type signature is a guess, might be slightly different
    gpioa.pa8.into_alternate_push_pull(&mut gpioa.crh)
}

The downside of doing that is that you can only have one init function that uses gpioa. I tend to do all my initialisation in one function for this reason.

Thanks for the explanation/confirmation!