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 2dc0e0a
Show file tree
Hide file tree
Showing 4 changed files with 32 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
28 changes: 28 additions & 0 deletions src/from_str.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
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(Angle { radians })

Check warning on line 13 in src/from_str.rs

View workflow job for this annotation

GitHub Actions / validate

unnecessary structure name repetition
}
}

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

#[test]
fn test_from_str() {
match "1.57".parse::<Angle>() {
Ok(angle) => assert_eq!(angle.radians, 1.57),
Err(_) => panic!("Could not parse angle"),
}
}
}
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 2dc0e0a

Please sign in to comment.