[][src]Crate safecast

safecast defines traits analogous to From, Into, TryFrom, and TryInto to standardize the implementation of casting between Rust types. The can_cast_from and can_cast_into methods borrow the source value, allowing pattern matching without moving.

Example:

let value = serde_json::from_str("1");
if value.matches::<i32>() {
    println!("It's an integer!");
} else if value.matches::<String>() {
    let value = String::opt_cast_from(value).unwrap();
    println!("no, it's a string: {}", value);
}

Traits

CastFrom

Trait for defining a cast operation from some source type T. Analogous to std::convert::From. The inverse of CastInto. Prefer implementing CastFrom over CastInto because implementing CastFrom automatically provides an implementation of CastInto.

CastInto

Trait for defining a cast operation to some destination type T. Analogous to std::convert::Into. The inverse of CastFrom. Prefer implementing CastFrom over CastInto because implementing CastFrom automatically provides an implementation of CastInto.

Match

Blanket implementation of a convenience method matches which allows calling can_cast_from with a type parameter. Do not implement this trait.

TryCastFrom

Trait for defining a cast operation when the source type cannot always be cast to the destination type. Defines a can_cast_from method which borrows the source value, allowing for pattern matching without moving the value. When can_cast_from returns true, calling opt_cast_from must return Some(...), otherwise try_cast_from may panic.

TryCastInto

Trait for defining a cast operation when the destination type cannot always be cast from the source type. Defines a can_cast_into method which borrows self, allowing for pattern matching without moving self. If can_cast_into returns true, then calling opt_cast_into must return Some(...), otherwise try_cast_into may panic.