rust-embedded / embedded-hal

A Hardware Abstraction Layer (HAL) for embedded systems
Apache License 2.0
1.95k stars 197 forks source link

Why do the SPI/I2C transaction slices have to be mutable? #504

Closed Dominaezzz closed 1 year ago

Dominaezzz commented 1 year ago

In the SPI transaction API and the I2C transaction API a mutable slice of operations is taken but I don't see why this is needed.

See Rust Playground example showing mut isn't necessary.

Rahix commented 1 year ago

Your playground example isn't complete as you are missing the immutable reference. Try putting the for loop into a function which takes &[...] and you'll notice it does not work anymore: https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=510670b534ad0a4fb665cd5aa2831362

The reason is that in your example the for loop operates on the owned array of operations ([Operation; 2]) while the function takes a reference to a slice (&[Operation]). In the latter case, even though there are mutable references inside the slice, the outer & prevents mutation of the data.

Dominaezzz commented 1 year ago

Ahhhh I see, thanks for the explanation.