pub trait ToRef<T: ?Sized> {
// Required method
fn to_ref(&self) -> &T;
}
Expand description
Trait for converting a value, reference, or mutable reference to an immutable reference.
This trait provides a unified interface to obtain an immutable reference from different types of ownership. It enables functions to work seamlessly with values, references, and mutable references by abstracting the conversion to a reference.
§Purpose
The ToRef
trait is useful in scenarios where a function or method needs to operate
on an immutable reference, regardless of whether the input is an owned value, a reference,
or a mutable reference. This abstraction simplifies the implementation of functions
that need to handle different ownership types uniformly.
§Example Usage
use mdmath_core::ToRef;
fn print_length< T : ToRef< String > >( input : T )
{
let reference = input.to_ref();
println!( "Length: {}", reference.len() );
}
let mut owned = String::from( "Hello" );
let borrowed = &owned;
print_length( borrowed );
let mut mutable_borrowed = &mut owned;
print_length( mutable_borrowed );
print_length( owned );