Skip to content

Implement Deref for &T #18621

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
kennytm opened this issue Nov 4, 2014 · 4 comments
Closed

Implement Deref for &T #18621

kennytm opened this issue Nov 4, 2014 · 4 comments

Comments

@kennytm
Copy link
Member

kennytm commented Nov 4, 2014

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());
@aturon
Copy link
Member

aturon commented Nov 6, 2014

cc @nikomatsakis

@nikomatsakis
Copy link
Contributor

yes I want this 👍

@Gankra
Copy link
Contributor

Gankra commented Nov 6, 2014

This would also allow code to be polymorphic over &T and &mut T by accepting Deref<T>. A huge win imho.

@aturon
Copy link
Member

aturon commented Nov 6, 2014

The branch here creates some trouble.

lnicola pushed a commit to lnicola/rust that referenced this issue Dec 11, 2024
fix: Resolve generic parameters within use captures
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants