From 2dc0e0afef8845a90c49572ac7898504de01e3ae Mon Sep 17 00:00:00 2001 From: Alexander van Trijffel Date: Sat, 19 Oct 2024 18:21:52 +0200 Subject: [PATCH] feat: FromStr --- README.md | 2 ++ src/from_str.rs | 28 ++++++++++++++++++++++++++++ src/graphemes.rs | 4 +--- src/lib.rs | 1 + 4 files changed, 32 insertions(+), 3 deletions(-) create mode 100644 src/from_str.rs diff --git a/README.md b/README.md index 45c770b..325e30a 100644 --- a/README.md +++ b/README.md @@ -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\ but instead implement the FromStr trait +- [graphemes](src/graphemes.rs) Trim an unicode string to a maximum length with ## Run the snippets diff --git a/src/from_str.rs b/src/from_str.rs new file mode 100644 index 0000000..8e274ce --- /dev/null +++ b/src/from_str.rs @@ -0,0 +1,28 @@ +use std::{num::ParseFloatError, str::FromStr}; + +pub struct Angle { + pub radians: f64, +} + +// Never implement From<&str> or From as FromStr is made for this +impl FromStr for Angle { + type Err = ParseFloatError; + + fn from_str(s: &str) -> Result { + let radians = s.parse::()?; + Ok(Angle { radians }) + } +} + +#[cfg(test)] +mod test { + use super::*; + + #[test] + fn test_from_str() { + match "1.57".parse::() { + Ok(angle) => assert_eq!(angle.radians, 1.57), + Err(_) => panic!("Could not parse angle"), + } + } +} diff --git a/src/graphemes.rs b/src/graphemes.rs index 1b04481..e818e59 100644 --- a/src/graphemes.rs +++ b/src/graphemes.rs @@ -1,8 +1,6 @@ -#![allow(dead_code)] - use unicode_segmentation::UnicodeSegmentation; -trait Trim { +pub trait Trim { fn trim_count(&self, count: usize) -> String; } diff --git a/src/lib.rs b/src/lib.rs index 072279b..bf79e15 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,3 +1,4 @@ +pub mod from_str; pub mod graphemes; pub mod mutate_in_closure; pub mod vec_any;