pub trait ZeroFrom<'zf, C: ?Sized>: 'zf {
    fn zero_from(other: &'zf C) -> Self;
Expand description

Trait for types that can be created from a reference to a different type C with no allocations, i.e. a zero-copy (zero-alloc) version of “From”

A type can be the ZeroFrom target of multiple other types.

The intention is for ZeroFrom to produce a struct from a other with as little work as possible. Although it is technically possible to implement ZeroFrom without being zero-copy (using heap allocations), doing so defeats the purpose of ZeroFrom.

For example, impl ZeroFrom<C> for Cow<str> should return a Cow::Borrowed pointing at data in the other type C, even if the other type is itself fully owned.

One can use the #[derive(ZeroFrom)] custom derive to automatically implement this trait.


Implementing ZeroFrom on a custom data struct:

use std::borrow::Cow;
use zerofrom::ZeroFrom;

struct MyStruct<'data> {
    message: Cow<'data, str>,

// Reference from a borrowed version of self
impl<'zf> ZeroFrom<'zf, MyStruct<'_>> for MyStruct<'zf> {
    fn zero_from(other: &'zf MyStruct<'_>) -> Self {
        MyStruct {
            message: Cow::Borrowed(&other.message),

// Reference from a string slice directly
impl<'zf> ZeroFrom<'zf, str> for MyStruct<'zf> {
    fn zero_from(other: &'zf str) -> Self {
        MyStruct {
            message: Cow::Borrowed(other),

Required Methods

Clone the other C into a struct that may retain references into C.

Implementations on Foreign Types