Skip to content

Commit

Permalink
feat: FromStr
Browse files Browse the repository at this point in the history
  • Loading branch information
alexandervantrijffel committed Oct 19, 2024
1 parent 0e08645 commit 85bbef7
Show file tree
Hide file tree
Showing 4 changed files with 29 additions and 3 deletions.
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ This repository offers some Rust snippets that might be useful when studying the

- [vec_any](src/vec_any.rs) Collect trait objects in a vector and use downcast_ref to access the concrete type instances of the items
- [mutate_in_closure](src/mutate_in_closure.rs) Mutate a value in a closure without copy and clone
- [from_str](src/from_str.rs) Thou shall not implement From\<str'> but instead implement the FromStr trait
- [graphemes](src/graphemes.rs) Trim an unicode string to a maximum length with

## Run the snippets

Expand Down
25 changes: 25 additions & 0 deletions src/from_str.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
use std::{num::ParseFloatError, str::FromStr};

pub struct Angle {
pub radians: f64,
}

// Never implement From<&str> or From<String> as FromStr is made for this
impl FromStr for Angle {
type Err = ParseFloatError;

fn from_str(s: &str) -> Result<Self, Self::Err> {
let radians = s.parse::<f64>()?;
Ok(Self { radians })
}
}

#[cfg(test)]
mod test {
use super::*;

#[test]
fn test_from_str() {
assert_eq!("1.57".parse::<Angle>().expect("Could not parse angle").radians, 1.57)
}
}
4 changes: 1 addition & 3 deletions src/graphemes.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
#![allow(dead_code)]

use unicode_segmentation::UnicodeSegmentation;

trait Trim {
pub trait Trim {
fn trim_count(&self, count: usize) -> String;
}

Expand Down
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
pub mod from_str;
pub mod graphemes;
pub mod mutate_in_closure;
pub mod vec_any;

0 comments on commit 85bbef7

Please sign in to comment.