Skip to content

Commit 2a98f19

Browse files
committed
Docs(preamble): Added rust examples
1 parent 858ba52 commit 2a98f19

File tree

1 file changed

+74
-0
lines changed

1 file changed

+74
-0
lines changed

docs/writing-reactors/preambles.mdx

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -440,6 +440,80 @@ The important takeaway here is with the package.json file and the compiled JavaS
440440

441441
<ShowIf rs>
442442

443+
For example, the follow reactor brings the constant `PI` into scope allowing us to call `f64::const::PI` as `PI`
444+
445+
```lf-c
446+
target Rust;
447+
448+
main reactor {
449+
preamble {=
450+
use std::f64::const::PI;
451+
=}
452+
453+
reaction(startup) {=
454+
println!("{}", PI);
455+
=}
456+
}
457+
```
458+
459+
This will print:
460+
461+
```
462+
3.141592653589793
463+
```
464+
for this example, we add the crate [hello](https://docs.rs/hello/latest/hello/) through the rust [cargo-dependencies](<../reference/target-declaration#cargo-dependencies>) target option.
465+
```lf-C
466+
target Rust {
467+
cargo-dependencies: {
468+
hello: "1.0.4",
469+
},
470+
};
471+
472+
preamble {=
473+
use hello;
474+
=}
475+
476+
main reactor {
477+
reaction(startup) {
478+
hello::world();
479+
}
480+
}
481+
482+
```
483+
This will print:
484+
```
485+
Hello, world!
486+
```
487+
488+
In this example we create a function `add_42` and a rust macro `add!`
489+
```lf-c
490+
target Rust;
491+
492+
main reactor {
493+
preamble {=
494+
macro_rules! add {
495+
($a:expr, $b:expr) => {
496+
$a+$b
497+
}
498+
}
499+
fn add_42 (a: i32) -> i32 {
500+
return a + 42;
501+
}
502+
=}
503+
504+
reaction(startup) {
505+
println!("add macro example: {}", add!(1,1));
506+
println!("add 42 example: {}", add_42(10));
507+
}
508+
}
509+
510+
```
511+
This will print:
512+
```
513+
add macro example: 2
514+
add 42 example: 52
515+
```
516+
443517
:::danger
444518
FIXME: Add `preamble` example.
445519
:::

0 commit comments

Comments
 (0)