Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/thiskai/sac
A rust macro for constructing collections
https://github.com/thiskai/sac
Last synced: 8 days ago
JSON representation
A rust macro for constructing collections
- Host: GitHub
- URL: https://github.com/thiskai/sac
- Owner: thisKai
- License: mit
- Created: 2018-04-27T15:28:21.000Z (over 6 years ago)
- Default Branch: master
- Last Pushed: 2019-08-16T16:44:47.000Z (over 5 years ago)
- Last Synced: 2024-10-13T01:48:01.052Z (about 1 month ago)
- Language: Rust
- Size: 26.4 KB
- Stars: 0
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# sac
[![Crates.io](https://img.shields.io/crates/v/sac.svg)](https://crates.io/crates/sac)
[![Documentation](https://docs.rs/sac/badge.svg)](https://docs.rs/sac)
![MIT License](https://img.shields.io/crates/l/sac.svg)A rust macro that will construct an instance of any collection that implements [FromIterator](https://doc.rust-lang.org/std/iter/trait.FromIterator.html).
## Cargo.toml
```toml
[dependencies]
sac = "0.2"
```## main.rs
```rust
#[macro_use]
extern crate sac;fn main() {
let vec: Vec<_> = sac![1, 2, 3, 4];
assert_eq!(vec, vec![1, 2, 3, 4]);
}
```No type annotations are needed if the compiler can infer the types:
```rust
struct VecWrapper(Vec);let container = VecWrapper(sac![1, 2, 3, 4]);
```Trailing commas are also supported:
```rust
let vec: Vec<_> = sac![
1,
2,
3,
4,
];assert_eq!(vec, vec![1, 2, 3, 4]);
```The macro can also construct maps (e.g. [HashMap](https://doc.rust-lang.org/std/collections/struct.HashMap.html)) with struct-like syntax:
```rust
use std::collections::HashMap;let map_with_syntax_sugar: HashMap<_, _> = sac! {
"foo": "bar",
"marco": "polo",
};let map_without_syntax_sugar: HashMap<_, _> = sac! [
("foo", "bar"),
("marco", "polo"),
];assert_eq!(map_with_syntax_sugar, map_without_syntax_sugar);
```Variables can be used as keys and values:
```rust
use std::collections::HashMap;let key = "foo";
let value = "bar";let map: HashMap<_, _> = sac! {
key: value,
};assert_eq!(map, sac! { "foo": "bar" });
```To use expressions as keys, surround them with parentheses or braces:
```rust
use std::collections::HashMap;let map: HashMap<_, _> = sac! {
(1 + 1): "two",
{2i32.pow(2)}: "four",
};assert_eq!(map, sac! { 2: "two", 4: "four" });
```