Converting between things in Rust
2021-08-08
Convert Result
to Option
: use ok()
.
let opt = res.ok();
Convert Option
to Result
: use ok_or()
.
let res = opt.ok_or("oh no");
Convert bool
to Option
: use then_some()
.
let res = boo.then_some(MyObject {});
Convert bool
to Result
: use then_some()
and ok_or()
.
let res = boo.then_some(MyObject {}).ok_or(MyError {})
Convert Result
to bool
: use is_ok()
.
let boo = res.is_ok();
Convert Option
to bool
: use is_some()
and is_none()
.
let is_some: bool = opt.is_some(); let is_none: bool = opt.is_none();
Convert str
to String
: use to_string().
let s: String = "str".to_string();
Convert String
to number (f64
, i32
, etc): use String::parse
.
let num = s.parse::<f64>()?;
1 ndarray conversions
Convert ndarray::ArrayView
to ndarray::Array
: use .to_owned()
.
Convert &[f64]
to ndarray::ArrayView
: use ArrayView3::from_shape
.
let arr: ndarray::Array3<f64> = ArrayView3::from_shape((3, height, width), slice)?.to_owned();
2 nalgebra conversions
Convert &[f64]
to na::DMatrixSlice
: use from_slice_with_strides