1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Traits for conversions between types.
13 //! The traits in this module provide a general way to talk about
14 //! conversions from one type to another. They follow the standard
15 //! Rust conventions of `as`/`to`/`into`/`from`.
17 #![unstable(feature = "convert",
18 reason = "recently added, experimental traits")]
22 /// A cheap, reference-to-reference conversion.
23 pub trait AsRef<T: ?Sized> {
24 /// Perform the conversion.
25 fn as_ref(&self) -> &T;
28 /// A cheap, mutable reference-to-mutable reference conversion.
29 pub trait AsMut<T: ?Sized> {
30 /// Perform the conversion.
31 fn as_mut(&mut self) -> &mut T;
34 /// A conversion that consumes `self`, which may or may not be
36 pub trait Into<T>: Sized {
37 /// Perform the conversion.
41 /// Construct `Self` via a conversion.
43 /// Perform the conversion.
47 ////////////////////////////////////////////////////////////////////////////////
49 ////////////////////////////////////////////////////////////////////////////////
52 impl<'a, T: ?Sized, U: ?Sized> Into<&'a U> for &'a T where T: AsRef<U> {
53 fn into(self) -> &'a U {
59 impl<'a, T: ?Sized, U: ?Sized> AsRef<U> for &'a T where T: AsRef<U> {
60 fn as_ref(&self) -> &U {
61 <T as AsRef<U>>::as_ref(*self)
66 impl<'a, T: ?Sized, U: ?Sized> AsRef<U> for &'a mut T where T: AsRef<U> {
67 fn as_ref(&self) -> &U {
68 <T as AsRef<U>>::as_ref(*self)
73 impl<'a, T: ?Sized, U: ?Sized> Into<&'a mut U> for &'a mut T where T: AsMut<U> {
74 fn into(self) -> &'a mut U {
79 // AsMut lifts over &mut
80 impl<'a, T: ?Sized, U: ?Sized> AsMut<U> for &'a mut T where T: AsMut<U> {
81 fn as_mut(&mut self) -> &mut U {
87 impl<T, U> Into<U> for T where U: From<T> {
93 ////////////////////////////////////////////////////////////////////////////////
95 ////////////////////////////////////////////////////////////////////////////////
97 impl<T> AsRef<[T]> for [T] {
98 fn as_ref(&self) -> &[T] {
103 impl<T> AsMut<[T]> for [T] {
104 fn as_mut(&mut self) -> &mut [T] {
109 impl AsRef<str> for str {
110 fn as_ref(&self) -> &str {