2

I'm quite new to rust and used to write code in other languages like JavaScript. My project is to code a program to control a cc2500 chip from my raspberry pi via rppal crate in Rust. So far it works but I'm searching for the right way.

Given: I have a list of unsigned 8bit integers and need a list of Segments with delay 20.

In JavaScript I would do it like this

let bytes = [0x7F, 0x55, ...]

let segments = bytes.map(byte => {
    let segment = Segment.with_write([byte]);
    segment.set_delay(20);
    return segment;
});

this.spi.transfer_segments(segments);

In rust I tried it like this

let bytes = vec![0x7F, 0x55, ...];

let mut segments:Vec<Segment> = vec![];
for (i, byte) in bytes.iter().enumerate() {
    let buffer = [byte.clone()];
    segments[i] = Segment::with_write(&buffer);
    segments[i].set_delay(20);
}

let written = self.spi.transfer_segments(&segments)
    .expect("Could not write to SPI bus");

But I always struggle with the ownership rules. How would you do this or what is the best practice?

1 Answer 1

4

Since all of your slices happen to be unary, you can use std::slice::from_ref to create them, pointing to the bytes from your bytes vector:

let bytes = vec![0x7F, 0x55, ...];

let segments = bytes.iter().map(|byte| {
    let buffer = std::slice::from_ref(byte);
    let mut segment = Segment::with_write(buffer);
    segment.set_delay(20);
    segment
});

let segments: Vec<_> = segments.collect().

let written = self.spi.transfer_segments(&segments)
    .expect("Could not write to SPI bus");
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.