Skip to main content

FromRouteSegments

Trait FromRouteSegments 

Source
pub trait FromRouteSegments: Sized {
    type Err: Display;

    // Required method
    fn from_route_segments(segments: &[&str]) -> Result<Self, Self::Err>;
}
Expand description

Something that can be created from multiple route segments. This must be implemented for any type that is spread into the route segment like #[route("/:..route_segments")].

This trait is automatically implemented for any types that implement FromIterator<impl Display>.

use dioxus::prelude::*;

#[derive(Routable, Clone, PartialEq, Debug)]
enum Route {
    // FromRouteSegments must be implemented for any types you use in the route segment
    // When you spread the route, you can parse multiple values from the route
    // This url will be in the format `/123/456/789`
    #[route("/:..numeric_route_segments")]
    Home {
        numeric_route_segments: NumericRouteSegments,
    },
}

// We can derive Default for NumericRouteSegments
// If the router fails to parse the route segment, it will use the default value instead
#[derive(Default, Clone, PartialEq, Debug)]
struct NumericRouteSegments {
    numbers: Vec<i32>,
}

// Implement ToRouteSegments for NumericRouteSegments so that we can display the route segments
impl ToRouteSegments for NumericRouteSegments {
    fn display_route_segments(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        for number in &self.numbers {
            write!(f, "/{}", number)?;
        }
        Ok(())
    }
}

// We also need to parse the route segments with `FromRouteSegments`
impl FromRouteSegments for NumericRouteSegments {
    type Err = <i32 as std::str::FromStr>::Err;

    fn from_route_segments(segments: &[&str]) -> Result<Self, Self::Err> {
        let mut numbers = Vec::new();
        for segment in segments {
            numbers.push(segment.parse()?);
        }
        Ok(NumericRouteSegments { numbers })
    }
}

Required Associated Types§

Source

type Err: Display

The error that can occur when parsing route segments.

Required Methods§

Source

fn from_route_segments(segments: &[&str]) -> Result<Self, Self::Err>

Create an instance of Self from route segments.

NOTE: This method must parse the output of ToRouteSegments::display_route_segments into the type Self.

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety".

Implementors§