Struct hashmap_settings::Stg
source · pub struct Stg { /* private fields */ }
Expand description
type abstraction for types implementing Setting
Types implementing Setting
can be turned into a Stg
with .stg().
use hashmap_settings::stg::{Setting,Stg};
let bool_stg: Stg = true.stg();
They can be turned back to a specific type with .unstg() or .unstg_panic()
let bool: bool = bool_stg.unstg()?;
Additionally there is the StgTrait
that can be implemented for types containing Stg
to allow
.unstg()
and .unstg_panic()
to be called on them.
The main example would be Option<&Stg>
use std::collections::HashMap;
use hashmap_settings::stg::{Setting,Stg,StgError,StgTrait};
let bool_stg: Stg = true.stg();
let mut hashmap = HashMap::new();
hashmap.insert("bool",bool_stg);
let bool: bool = hashmap.get("bool").unstg()?;
Implementations§
source§impl Stg
impl Stg
sourcepub fn unstg<S: Setting>(self) -> Result<S, Box<dyn Any>>
pub fn unstg<S: Setting>(self) -> Result<S, Box<dyn Any>>
turns a Stg
into a Result<S, Box<dyn Any>>
´unstg´ is the main and safe way to used to get a concrete type S
from Stg
Consider using unstg_panic
if it’s guaranteed that we will convert to the right type.
§Example
use hashmap_settings::stg::{Setting,Stg};
let bool_stg: Stg = true.stg();
assert_eq!(bool_stg.unstg::<bool>()?, true);
//we need to use ::<bool> to specify that want to turn bool_stg into a bool
use hashmap_settings::stg::{Setting,Stg};
let bool_stg: Stg = true.stg();
let bool :bool = bool_stg.unstg()?;
// here we don't as we specific the type annotation when we use :bool
assert_eq!(bool, true);
§Errors
This function returns a Err(Box<dyn Any>)
if we try to covert to the wrong type.
use hashmap_settings::stg::{Setting,Stg};
let bool_stg: Stg = true.stg();
let number = match bool_stg.unstg::<i32>(){
Ok(x) => x, //unreachable!()
Err(x) => {
print!("wrong conversion {:?}",x);
404
},
};
assert_eq!(number, 404)
sourcepub fn unstg_panic<S: Setting>(self) -> S
pub fn unstg_panic<S: Setting>(self) -> S
turns a Stg
into a concrete type S
, can panic!
This method is used to get a concrete type out of a Stg
when it’s know what S
it contains.
§Panics
We need to be careful using unstg_panic
as if we try convert to a type
that isn’t the one contained in Stg
the program will panic.
Consider using unstg
as it returns a result type instead.
use hashmap_settings::stg::{Setting,Stg};
let bool_stg: Stg = true.stg();
let _number :i32 = bool_stg.unstg_panic();
// this panics, as the Box<dyn Setting> holds a bool value but we are trying to convert it to a i32
§Examples
use hashmap_settings::stg::{Setting,Stg};
let bool_stg: Stg = true.stg();
assert_eq!(bool_stg.unstg_panic::<bool>(), true);
//we need to use ::<bool> to specify that want to turn bool_stg into a bool
use hashmap_settings::stg::{Setting,Stg};
let bool_stg: Stg = true.stg();
let bool :bool = bool_stg.unstg_panic();
// here we don't as we specific the type annotation when we use :bool
assert_eq!(bool, true);