Skip to content

Commit

Permalink
exampl
Browse files Browse the repository at this point in the history
  • Loading branch information
szabgab committed Jul 18, 2024
1 parent 41cd867 commit fc8adb3
Show file tree
Hide file tree
Showing 5 changed files with 54 additions and 1 deletion.
7 changes: 7 additions & 0 deletions slides/rust/examples/macros/optional-parameter/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 6 additions & 0 deletions slides/rust/examples/macros/optional-parameter/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
[package]
name = "optional-parameter"
version = "0.1.0"
edition = "2021"

[dependencies]
8 changes: 8 additions & 0 deletions slides/rust/examples/macros/optional-parameter/out.out
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
ping localhost
ping remote
ping remote
ping remote
ping remote
ping localhost
ping localhost
ping localhost
27 changes: 27 additions & 0 deletions slides/rust/examples/macros/optional-parameter/src/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
macro_rules! ping {

($address: expr) => {
ping($address, 4);
};
($address: expr, $repeat: expr) => {
ping($address, $repeat);
};
}

fn ping(address: &str, mut repeat: u8) {
while repeat > 0 {
println!("ping {address}");
repeat -= 1;
}
}
fn main() {
ping("localhost", 1);

//ping("remote");
ping!("remote");

ping!("localhost", 3);
}



7 changes: 6 additions & 1 deletion slides/rust/macros.md
Original file line number Diff line number Diff line change
Expand Up @@ -116,13 +116,18 @@ cargo run bar


## Macro ok! to replace unwrap
{id: macri-ok}
{id: macro-ok}

Seen in the tests of the sqlite crate.

```
macro_rules! ok(($result:expr) => ($result.unwrap()));
```

## Optional function parameters using macros
{id: optional-function-parameters-using-macro}

![](examples/macros/optional-parameter/src/main.rs)
![](examples/macros/optional-parameter/out.out)


0 comments on commit fc8adb3

Please sign in to comment.