Trait FromRouteSegment

Source
pub trait FromRouteSegment: Sized {
    type Err;

    // Required method
    fn from_route_segment(route: &str) -> Result<Self, Self::Err>;
}
Expand description

Something that can be created from a single route segment. This must be implemented for any type that is used as a route segment like #[route("/:route_segment")].

This trait is automatically implemented for any types that implement FromStr and Default.

use dioxus::prelude::*;

#[derive(Routable, Clone, PartialEq, Debug)]
enum Route {
    // FromRouteSegment must be implemented for any types you use in the route segment
    // When you don't spread the route, you can parse multiple values from the route
    // This url will be in the format `/123/456`
    #[route("/:route_segment_one/:route_segment_two")]
    Home {
        route_segment_one: CustomRouteSegment,
        route_segment_two: i32,
    },
}

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

// We implement FromStr for CustomRouteSegment so that FromRouteSegment is implemented automatically
impl std::str::FromStr for CustomRouteSegment {
    type Err = <i32 as std::str::FromStr>::Err;

    fn from_str(route_segment: &str) -> Result<Self, Self::Err> {
        Ok(CustomRouteSegment {
            count: route_segment.parse()?,
        })
    }
}

// We also need to implement Display for CustomRouteSegment which will be used to format the route segment into the URL
impl std::fmt::Display for CustomRouteSegment {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.count)
    }
}

Required Associated Types§

Source

type Err

The error that can occur when parsing a route segment.

Required Methods§

Source

fn from_route_segment(route: &str) -> Result<Self, Self::Err>

Create an instance of Self from a route segment.

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.

Implementors§

Source§

impl<T: FromStr> FromRouteSegment for T
where <T as FromStr>::Err: Display,

Source§

type Err = <T as FromStr>::Err