]> git.lizzy.rs Git - rust.git/blob - src/libstd/to_str.rs
auto merge of #15374 : steveklabnik/rust/comments, r=brson
[rust.git] / src / libstd / to_str.rs
1 // Copyright 2012-2013 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.
4 //
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.
10
11 /*!
12
13 The `ToString` trait for converting to strings
14
15 */
16
17 #![experimental]
18
19 use fmt;
20 use string::String;
21
22 /// A generic trait for converting a value to a string
23 pub trait ToString {
24     /// Converts the value of `self` to an owned string
25     fn to_string(&self) -> String;
26 }
27
28 /// Trait for converting a type to a string, consuming it in the process.
29 pub trait IntoStr {
30     /// Consume and convert to a string.
31     fn into_string(self) -> String;
32 }
33
34 impl<T: fmt::Show> ToString for T {
35     fn to_string(&self) -> String {
36         format!("{}", *self)
37     }
38 }
39
40 #[cfg(test)]
41 mod tests {
42     use prelude::*;
43     use super::*;
44
45     #[test]
46     fn test_simple_types() {
47         assert_eq!(1i.to_string(), "1".to_string());
48         assert_eq!((-1i).to_string(), "-1".to_string());
49         assert_eq!(200u.to_string(), "200".to_string());
50         assert_eq!(2u8.to_string(), "2".to_string());
51         assert_eq!(true.to_string(), "true".to_string());
52         assert_eq!(false.to_string(), "false".to_string());
53         assert_eq!(().to_string(), "()".to_string());
54         assert_eq!(("hi".to_string()).to_string(), "hi".to_string());
55     }
56
57     #[test]
58     fn test_vectors() {
59         let x: Vec<int> = vec![];
60         assert_eq!(x.to_string(), "[]".to_string());
61         assert_eq!((vec![1i]).to_string(), "[1]".to_string());
62         assert_eq!((vec![1i, 2, 3]).to_string(), "[1, 2, 3]".to_string());
63         assert!((vec![vec![], vec![1i], vec![1i, 1]]).to_string() ==
64                "[[], [1], [1, 1]]".to_string());
65     }
66 }