Crates.io | ident |
lib.rs | ident |
version | 0.3.10 |
source | src |
created_at | 2018-03-12 15:23:54.985121 |
updated_at | 2018-08-03 10:20:26.58625 |
description | A utility crate for wrapping types with an immutable identifier and storing/accessing such types in collections. |
homepage | |
repository | https://github.com/Dynisious/ident |
max_upload_size | |
id | 55173 |
size | 24,042 |
A Rust utility crate for wrapping types with an immutable identifier and storing/accessing such types in collections by that identifier.
First add the crate to your Cargo.toml
:
[dependencies]
ident = "*" # or the specific version you want to use.
And import the crate to your own main.rs
/lib.rs
:
extern crate ident;
use ident::*;
Lets say you have some type:
#[derive(Clone)]
struct Foo {
x: usize
}
impl Foo {
pub fn new(x: usize) -> Self {
Self { x }
}
pub fn do_stuff(&mut self) {
//Your code.
}
}
And you have a collection of Foo
s
use std::collections::HashMap;
fn main() {
let mut my_foos = HashMap::with_capacity(2);
my_foos.insert(5, Foo::new(10));
my_foos.insert(10, Foo::new(5));
let mut foo = my_foos.get(&5).unwrap().clone();
foo.do_stuff();
}
Its often useful to remember where you got you value from (my_foos[5]
in this case). That would normally mean creating a new variable which you have to remember to pass everywhere but with ident
:
use ident::*;
use std::collections::HashMap;
fn main() {
let mut my_foos = HashMap::with_capacity(2);
my_foos.insert(5, Foo::new(10));
my_foos.insert(10, Foo::new(5));
let mut foo = WithIdent::new(5, my_foos.get(5).unwrap().clone());
foo.do_stuff();
}
We are able to get the key bundled with the value while still accessing the value as if the key wasn't there.
This is a simple use case however:
WithIdent
which allow you to manipulate the inner value or the identifier as needed.