Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/oxeu/kotlike
A Rust macro to modify the question mark operator's behavior just like Kotlin's
https://github.com/oxeu/kotlike
crates macro macros-rust rust
Last synced: about 4 hours ago
JSON representation
A Rust macro to modify the question mark operator's behavior just like Kotlin's
- Host: GitHub
- URL: https://github.com/oxeu/kotlike
- Owner: OXeu
- License: apache-2.0
- Created: 2024-01-07T15:09:31.000Z (10 months ago)
- Default Branch: master
- Last Pushed: 2024-01-07T15:47:38.000Z (10 months ago)
- Last Synced: 2024-10-12T17:43:03.994Z (24 days ago)
- Topics: crates, macro, macros-rust, rust
- Language: Rust
- Homepage:
- Size: 10.7 KB
- Stars: 4
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
Kotlike
A Rust macro to modify the question mark operator's behavior just like Kotlin's
With it, you can easily pick out the value wrapped in numberless `Option` and `Result`.
Furthermore, it won't break down your control flow. You can continue your work even you got a `None` or `Err` (All the unexpected value will turn to `None`)
It means:
```rust
fn do_something() {
let value: Option = wrapped_value?.something_return_option()?.something_return_result()?.value;
}
```
would works fine! Just as Kotlin's style.
And you don't need to worry about what `Err` it would throw!# How it Works
**Usage**
```rust
#[kotlike]
fn main() {
let a = "Hello".to_string();
let c = File::create("test.txt")?.write_all(a.as_bytes())?.clone();
let mut b: String = String::new();
let len = File::open("test.txt")?.read_to_string(&mut b)?.clone();
println!("Hello, {:?}({:?})!", b,len);
}
```
**Expand the macro would look like**:
```rust
fn main() {
let a = "Hello".to_string();
let c: Option<()> = File::create("test.txt")
.map_or(None, |mut v| {
v.write_all(a.as_bytes())
.map_or(None, |mut v| Some(v.clone()))
});
let mut b: String = String::new();
let len: Option = File::open("test.txt")
.map_or(None, |mut v|{
v.read_to_string(&mut b)
.map_or(None, |mut v| Some(v.clone()))
});
println!("Hello, {:?}({:?})!", b,len);
}
```
Above example is just showing how it works. Don't focus too much on what stupid code does.# LICENSE
[Apache LICENSE 2.0](LICENSE)