Skip to content

Commit

Permalink
make rust examples editable
Browse files Browse the repository at this point in the history
  • Loading branch information
john-cd committed Dec 23, 2023
1 parent 89ddebc commit 7537ea6
Show file tree
Hide file tree
Showing 42 changed files with 225 additions and 169 deletions.
10 changes: 5 additions & 5 deletions src/concerns/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

It supersedes [dotenv]( https://crates.io/crates/dotenv )

```rust,ignore
```rust,editable,ignore
use std::env;
use std::error::Error;
Expand All @@ -25,7 +25,7 @@ fn main() -> Result<(), Box<dyn Error>> {

To retrieve a single environment variable

```rust,ignore
```rust,editable,ignore
use std::env;
fn env_extract() -> String {
Expand All @@ -35,7 +35,7 @@ fn env_extract() -> String {
let shell = env!("SHELL", "$SHELL is not set"); // inspect an environment variable at compile-time.
let optional_value = option_env!("SHELL");
let optional_value = option_env!("SHELL");
return optional_value
.unwrap_or("no shell set")
Expand All @@ -59,7 +59,7 @@ envy = "0.4"
serde = { version = "1.0", features = ["derive"] }
```

```rust,ignore
```rust,editable,ignore
use serde::Deserialize;
#[derive(Deserialize, Debug)]
Expand All @@ -86,7 +86,7 @@ fn main() {

[Confy]( https://docs.rs/confy/latest/confy/index.html )

```rust,ignore
```rust,editable,ignore
use serde::{Serialize, Deserialize};
#[derive(Serialize, Deserialize)]
Expand Down
6 changes: 3 additions & 3 deletions src/concerns/derive.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ The `derive` attribute generates code that will implement a trait with its own d

[Derivable traits]( https://doc.rust-lang.org/book/appendix-03-derivable-traits.html )

```rust
// on structs
```rust,editable
// on structs
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Hash, Default)]
struct S(i32);
Expand All @@ -21,7 +21,7 @@ You can use the `cargo-expand` utility to see the exact code that is generated f

[Derive More]( https://crates.io/crates/derive_more ) derive lots of additional, commonly used traits and static methods for both structs and enums.

```rust,ignore
```rust,editable,ignore
extern crate derive_more;
use derive_more::{Add, Display, From, Into};
Expand Down
8 changes: 4 additions & 4 deletions src/concerns/documentation.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,14 @@

1) Add documentation comments to your code.

```rust,ignore
```rust,editable,ignore
/// This is a doc comment. It is equivalent to the next line.
#[doc = r" This is a doc comment."]
```

`rustdoc` uses the CommonMark Markdown specification.

```rust,ignore
```rust,editable,ignore
/// Returns a person with the name given them
///
/// # Arguments
Expand Down Expand Up @@ -47,7 +47,7 @@ Use `//!` at the top of the file (instead of `///`) for module-level documentati
The first lines within `lib.rs` will compose the crate-level documentation front-page.
```rust,ignore
```rust,editable,ignore
//! Fast and easy queue abstraction.
//!
//! Provides an abstraction over a queue. When the abstraction is used
Expand All @@ -60,7 +60,7 @@ The first lines within `lib.rs` will compose the crate-level documentation front

- To add a "run" button on your documentation (allowing its execution in the rust playground), use the following attribute:

```rust,ignore
```rust,editable,ignore
#![doc(html_playground_url = "https://playground.example.com/")]
```

Expand Down
10 changes: 5 additions & 5 deletions src/concerns/error_customization.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ Use `thiserror` if you are a library that wants to design your own dedicated err

Use `Result<T, anyhow::Error>` or equivalently `anyhow::Result<T>` as the return type of any fallible function.

```rust,ignore
```rust,editable,ignore
use anyhow::{Context, Result};
fn main() -> Result<()> {
Expand All @@ -27,7 +27,7 @@ Anyhow works with any error type that has an impl of `std::error::Error`, includ

[thisError]( https://docs.rs/thiserror/latest/thiserror/ ) provides a convenient `derive` macro for the standard library’s `std::error::Error` trait.

```rust,ignore
```rust,editable,ignore
use thiserror::Error;
#[derive(Error, Debug)]
Expand Down Expand Up @@ -57,14 +57,14 @@ fn main() {}

The `#[error(...)]` messages support a shorthand for interpolating fields from the error.

```rust,ignore
```rust,editable,ignore
#[error("{var}")] ⟶ write!("{}", self.var)
#[error("{0}")] ⟶ write!("{}", self.0)
#[error("{var:?}")] ⟶ write!("{:?}", self.var)
#[error("{0:?}")] ⟶ write!("{:?}", self.0)
```

```rust,ignore
```rust,editable,ignore
#[derive(Error, Debug)]
pub struct MyError {
msg: String,
Expand All @@ -81,7 +81,7 @@ fn main() {}

[Miette]( https://lib.rs/crates/miette ) prints fancy diagnostics upon error.

```rust,ignore
```rust,editable,ignore
use miette::{Diagnostic, SourceSpan, NamedSource};
// In library code, `thiserror` plays nicely with `miette` to define unique error types and error wrappers
Expand Down
14 changes: 7 additions & 7 deletions src/concerns/error_handling.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,25 +2,25 @@

## Irrecoverable panics

```rust,ignore
panic!("crash and burn");
```rust,editable,ignore
panic!("crash and burn");
```

## Recoverable errors with `Result`

```rust,ignore
```rust,editable,ignore
let mut guess = String::new();
io::stdin()
.read_line(&mut guess) // read_line puts whatever the user enters into the string we pass to it, but it also returns a Result value.
.expect("Failed to read line"); // If this instance of Result is an Err value, expect will cause the program to crash and display the message that you passed as an argument to expect.
.expect("Failed to read line"); // If this instance of Result is an Err value, expect will cause the program to crash and display the message that you passed as an argument to expect.
let greeting_file = File::open("hello.txt").unwrap(); // alternative: panics if error - no message
```

### unwrap_or_else

```rust,ignore
```rust,editable,ignore
use std::fs::File;
use std::io::ErrorKind;
Expand All @@ -39,7 +39,7 @@ fn main() {

## A Shortcut for Propagating Errors: the ? Operator

```rust,ignore
```rust,editable,ignore
use std::fs::File;
use std::io::{self, Read};
Expand All @@ -59,7 +59,7 @@ This error points out that we’re only allowed to use the `?` operator in a fun

Another example:

```rust
```rust,editable
use std::error::Error;
fn parse_port(s: &str) -> Result<u16, Box<dyn Error>> { // needed to use Box<dyn Error>, because the returned error type cannot be determined during compile time: It will either contain an instance of std::num::ParseIntError (from the parse method, when parsing fails), or a string (when the port is zero).
Expand Down
4 changes: 2 additions & 2 deletions src/concerns/lazy_initialization.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

The corresponding Sync version of `OnceCell<T>` is `OnceLock<T>`.

```rust
```rust,editable
use std::cell::OnceCell;
fn main() {
Expand All @@ -27,7 +27,7 @@ fn main() {

once_cell also has a `Lazy<T>` type, build on top of `OnceCell`:

```rust,ignore
```rust,editable,ignore
use std::{sync::Mutex, collections::HashMap};
use once_cell::sync::Lazy;
Expand Down
22 changes: 13 additions & 9 deletions src/concerns/logging.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ tracing-subscriber = "0.3"

Basic tracing

```rust,ignore
```rust,editable,ignore
use tracing_subscriber;
fn main() {
Expand All @@ -26,7 +26,7 @@ fn main() {

Combine layers

```rust,ignore
```rust,editable,ignore
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};
fn main() {
Expand All @@ -43,7 +43,7 @@ fn main() {

Or with a custom formatting layer

```rust,ignore
```rust,editable,ignore
use tracing_subscriber::{fmt, EnvFilter};
use tracing_subscriber::prelude::*;
Expand All @@ -63,7 +63,7 @@ fn main() {

Configure a custom event formatter

```rust,ignore
```rust,editable,ignore
use tracing_subscriber::fmt;
fn main() {
Expand All @@ -84,7 +84,7 @@ fn main() {

## Events

```rust,ignore
```rust,editable,ignore
use tracing::{event, error, warn, info, debug, trace, Level};
fn main() {
Expand Down Expand Up @@ -114,7 +114,7 @@ fn main() {

## Spans

```rust,ignore
```rust,editable,ignore
use tracing::{span, Level};
fn main() {
Expand All @@ -130,7 +130,7 @@ fn main() {

One-liner with `.entered()`:

```rust,ignore
```rust,editable,ignore
use tracing::{span, Level};
fn main() {
Expand All @@ -150,7 +150,7 @@ fn main() {

Holding the drop guard returned by `Span::enter` across `.await` points will result in incorrect traces. Use `in_scope`

```rust,ignore
```rust,editable,ignore
async fn my_async_function() {
let span = info_span!("my_async_function");
Expand Down Expand Up @@ -180,7 +180,7 @@ async fn my_async_function() {

## Add tracing spans to functions

```rust,ignore
```rust,editable,ignore
use tracing::{Level, event, instrument};
#[instrument]
Expand All @@ -201,3 +201,7 @@ async fn my_async_function() {
some_other_async_function().await;
}
```

## OpenTelemetry

[OpenTelemetry Rust documentation]( https://opentelemetry.io/docs/instrumentation/rust/ )
12 changes: 6 additions & 6 deletions src/concerns/tests.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,17 @@
`cargo test test_prefix` to run all tests that start with the provided prefix.
`cargo test -- --show-output` to show output (println!) that is otherwise captured during tests.

```rust
```rust,editable
// in the same file than the main code
#[cfg(test)] // only for unit tests
#[cfg(test)] // only for unit tests
mod tests {
use super::*; // access to all objects in the parent module, which contains the main code
// Test functions must be free, monomorphic functions that take no arguments,
// Test functions must be free, monomorphic functions that take no arguments,
// and commonly return () or Result<T, E> where T: Termination, E: Debug
#[test]
fn larger_can_hold_smaller() {
fn larger_can_hold_smaller() {
let larger = Rectangle {
width: 8,
height: 7,
Expand All @@ -24,7 +24,7 @@ mod tests {
height: 1,
};
assert!(larger.can_hold(&smaller));
assert!(larger.can_hold(&smaller));
// or assert_eq!(result, some_const);
// or assert_ne!
}
Expand Down Expand Up @@ -58,7 +58,7 @@ fn main() {}

Custom message:

```rust,ignore
```rust,editable,ignore
fn main() {
assert!(
result.contains("Carol"),
Expand Down
52 changes: 52 additions & 0 deletions src/concurrency/actors.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
# Actors

## Stakker


## Riker

[Riker]( https://riker.rs/ )

```rust,editable,ignore
struct MyActor;
impl Actor for MyActor {
type Msg = String;
fn recv(&mut self,
ctx: &Context<String>,
msg: String,
sender: Sender) {
println!("received {}", msg);
}
}
fn main() {
let sys = SystemBuilder::new()
.name("my-app")
.create()
.unwrap();
// Every actor has a name that is required to be unique among its singlings (those actors sharing the same parent actor).
let my_actor = sys.actor_of::<MyActor>("my-actor").unwrap();
my_actor.tell("Hello!".to_string(), None);
// force main to wait before exiting program
std::thread::sleep(Duration::from_millis(500));
}
```

## Alternatives

[Actix]( https://github.com/actix/actix )

[Ractor]( https://crates.io/crates/ractor )

## Utilities

[Await tree]( https://crates.io/crates/await-tree )

## Reference

[Actors with Tokio]( https://ryhl.io/blog/actors-with-tokio/ )
Loading

0 comments on commit 7537ea6

Please sign in to comment.