---
title: "Converting between things in Rust"
date: "2021-08-08"
---


Convert `Result` to `Option`: use `ok()`.

```rust
let opt = res.ok();
```

Convert `Option` to `Result`: use `ok_or()`.

```rust
let res = opt.ok_or("oh no");
```

Convert `bool` to `Option`: use `then_some()`.

```rust
let res = boo.then_some(MyObject {});
```

Convert `bool` to `Result`: use `then_some()` and `ok_or()`.

```rust
let res = boo.then_some(MyObject {}).ok_or(MyError {})
```

Convert `Result` to `bool`: use `is_ok()`.

```rust
let boo = res.is_ok();
```

Convert `Option` to `bool`: use `is_some()` and `is_none()`.

```rust
let is_some: bool = opt.is_some();
let is_none: bool = opt.is_none();
```

Convert `str` to `String`: use `to_string().`

```rust
let s: String = "str".to_string();
```

Convert `String` to number (`f64`, `i32`, etc): use `String::parse`.

```rust
let num = s.parse::<f64>()?;
```

# ndarray conversions

Convert `ndarray::ArrayView` to `ndarray::Array`: use `.to_owned()`.

Convert `&[f64]` to `ndarray::ArrayView`: use `ArrayView3::from_shape`.

```rust
let arr: ndarray::Array3<f64> = ArrayView3::from_shape((3, height, width), slice)?.to_owned();
```

# nalgebra conversions

Convert `&[f64]` to `na::DMatrixSlice`: use `from_slice_with_strides`
