Skip to content

Implement Deref for &T #18621

Closed
Closed
@kennytm

Description

@kennytm

As titled. Add the following trait implementations:

impl<'a, Sized? T> Deref<T> for &'a T {
    fn deref(&self) -> &T { *self }
}
impl<'a, Sized? T> Deref<T> for &'a mut T {
    fn deref(&self) -> &S { *self }
}
impl<'a, Sized? T> DerefMut<T> for &'a mut T {
    fn deref_mut(&mut self) -> &mut T { *self }
}

This allows generic code that accepts smart pointer can take references too, e.g.

fn sum_pointers<V: Deref<int>>(v: &[V]) -> int;
sum_pointers([Rc::new(1i), Rc::new(2i)]);
sum_pointers([&1i, &2i, &3i]);

fn sum_2d<V: Deref<[int]>>(v: &[V]) -> int;
sum_2d(vec![vec![2,3], vec![4,5,6]].as_slice());
sum_2d([[2,3].as_slice(), [4,5,6].as_slice()].as_slice());

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions