From 76e234599f6da0b7ee21b98da80201a3984ee323 Mon Sep 17 00:00:00 2001 From: Emil Fresk Date: Thu, 7 Nov 2019 14:12:16 +0100 Subject: [PATCH] Added struct de-structure-ing example in tips & tricks --- book/en/src/by-example/tips.md | 9 +++++++ examples/destructure.rs | 47 ++++++++++++++++++++++++++++++++++ 2 files changed, 56 insertions(+) create mode 100644 examples/destructure.rs diff --git a/book/en/src/by-example/tips.md b/book/en/src/by-example/tips.md index a0082060a9..b923ed0850 100644 --- a/book/en/src/by-example/tips.md +++ b/book/en/src/by-example/tips.md @@ -165,3 +165,12 @@ crate and print the output to the console. $ # produces the same output as before $ cargo expand --example smallest | tail ``` + +## Resource de-structure-ing + +When having a task taking multiple resources it can help in readability to split +up the resource struct. Here're two examples on how this can be done: + +``` rust +{{#include ../../../../examples/destructure.rs}} +``` diff --git a/examples/destructure.rs b/examples/destructure.rs new file mode 100644 index 0000000000..0cc3c1f1c2 --- /dev/null +++ b/examples/destructure.rs @@ -0,0 +1,47 @@ +//! examples/destructure.rs + +#![deny(unsafe_code)] +#![deny(warnings)] +#![no_main] +#![no_std] + +use cortex_m_semihosting::hprintln; +use lm3s6965::Interrupt; +use panic_semihosting as _; + +#[rtfm::app(device = lm3s6965)] +const APP: () = { + struct Resources { + // Some resources to work with + #[init(0)] + a: u32, + #[init(0)] + b: u32, + #[init(0)] + c: u32, + } + + #[init] + fn init(_: init::Context) { + rtfm::pend(Interrupt::UART0); + rtfm::pend(Interrupt::UART1); + } + + // Direct destructure + #[task(binds = UART0, resources = [a, b, c])] + fn uart0(cx: uart0::Context) { + let a = cx.resources.a; + let b = cx.resources.b; + let c = cx.resources.c; + + hprintln!("UART0: a = {}, b = {}, c = {}", a, b, c).unwrap(); + } + + // De-structure-ing syntax + #[task(binds = UART1, resources = [a, b, c])] + fn uart1(cx: uart1::Context) { + let uart1::Resources { a, b, c } = cx.resources; + + hprintln!("UART0: a = {}, b = {}, c = {}", a, b, c).unwrap(); + } +};