]> git.lizzy.rs Git - rust.git/blob - src/doc/complement-cheatsheet.md
std: Remove format_strbuf!()
[rust.git] / src / doc / complement-cheatsheet.md
1 % Rust Cheatsheet
2
3 # How do I convert *X* to *Y*?
4
5 **Int to string**
6
7 Use [`ToStr`](../std/to_str/trait.ToStr.html).
8
9 ~~~
10 let x: int = 42;
11 let y: String = x.to_str().to_string();
12 ~~~
13
14 **String to int**
15
16 Use [`FromStr`](../std/from_str/trait.FromStr.html), and its helper function,
17 [`from_str`](../std/from_str/fn.from_str.html).
18
19 ~~~
20 let x: Option<int> = from_str("42");
21 let y: int = x.unwrap();
22 ~~~
23
24 **Int to string, in non-base-10**
25
26 Use the `format!` syntax extension.
27
28 ~~~
29 let x: int = 42;
30 let y: String = format!("{:t}", x);   // binary
31 let y: String = format!("{:o}", x);   // octal
32 let y: String = format!("{:x}", x);   // lowercase hexadecimal
33 let y: String = format!("{:X}", x);   // uppercase hexadecimal
34 ~~~
35
36 **String to int, in non-base-10**
37
38 Use [`FromStrRadix`](../std/num/trait.FromStrRadix.html), and its helper
39 function, [`from_str_radix`](../std/num/fn.from_str_radix.html).
40
41 ~~~
42 use std::num;
43
44 let x: Option<i64> = num::from_str_radix("deadbeef", 16);
45 let y: i64 = x.unwrap();
46 ~~~
47
48 **Vector of Bytes to String**
49
50 To return a Borrowed String Slice (&str) use the str helper function
51 [`from_utf8`](../std/str/fn.from_utf8.html).
52
53 ~~~
54 use std::str;
55
56 let bytes = ~[104u8,105u8];
57 let x: Option<&str> = str::from_utf8(bytes);
58 let y: &str = x.unwrap();
59 ~~~
60
61 To return an Owned String use the str helper function
62 [`from_utf8_owned`](../std/str/fn.from_utf8_owned.html).
63
64 ~~~
65 use std::str;
66
67 let x: Option<String> =
68     str::from_utf8([ 104u8, 105u8 ]).map(|x| x.to_string());
69 let y: String = x.unwrap();
70 ~~~
71
72 To return a [`MaybeOwned`](../std/str/enum.MaybeOwned.html) use the str helper
73 function [`from_utf8_lossy`](../std/str/fn.from_utf8_owned.html).
74 This function also replaces non-valid utf-8 sequences with U+FFFD replacement
75 character.
76
77 ~~~
78 use std::str;
79
80 let x = bytes!(72u8,"ello ",0xF0,0x90,0x80,"World!");
81 let y = str::from_utf8_lossy(x);
82 ~~~
83
84 # File operations
85
86 ## How do I read from a file?
87
88 Use
89 [`File::open`](../std/io/fs/struct.File.html#method.open)
90 to create a
91 [`File`](../std/io/fs/struct.File.html)
92 struct, which implements the
93 [`Reader`](../std/io/trait.Reader.html)
94 trait.
95
96 ~~~ {.ignore}
97 use std::path::Path;
98 use std::io::fs::File;
99
100 let path : Path   = Path::new("Doc-FAQ-Cheatsheet.md");
101 let on_error      = || fail!("open of {:?} failed", path);
102 let reader : File = File::open(&path).unwrap_or_else(on_error);
103 ~~~
104
105 ## How do I iterate over the lines in a file?
106
107 Use the [`lines`](../std/io/trait.Buffer.html#method.lines) method on a [`BufferedReader`](../std/io/buffered/struct.BufferedReader.html).
108
109 ~~~
110 use std::io::BufferedReader;
111 # use std::io::MemReader;
112
113 # let reader = MemReader::new(vec!());
114
115 let mut reader = BufferedReader::new(reader);
116 for line in reader.lines() {
117     print!("line: {}", line);
118 }
119 ~~~
120
121 # String operations
122
123 ## How do I search for a substring?
124
125 Use the [`find_str`](../std/str/trait.StrSlice.html#tymethod.find_str) method.
126
127 ~~~
128 let str = "Hello, this is some random string";
129 let index: Option<uint> = str.find_str("rand");
130 ~~~
131
132 # Containers
133
134 ## How do I get the length of a vector?
135
136 The [`Container`](../std/container/trait.Container.html) trait provides the `len` method.
137
138 ~~~
139 let u: ~[u32] = ~[0, 1, 2];
140 let v: &[u32] = &[0, 1, 2, 3];
141 let w: [u32, .. 5] = [0, 1, 2, 3, 4];
142
143 println!("u: {}, v: {}, w: {}", u.len(), v.len(), w.len()); // 3, 4, 5
144 ~~~
145
146 ## How do I iterate over a vector?
147
148 Use the [`iter`](../std/vec/trait.ImmutableVector.html#tymethod.iter) method.
149
150 ~~~
151 let values: ~[int] = ~[1, 2, 3, 4, 5];
152 for value in values.iter() {  // value: &int
153     println!("{}", *value);
154 }
155 ~~~
156
157 (See also [`mut_iter`](../std/vec/trait.MutableVector.html#tymethod.mut_iter)
158 which yields `&mut int` and
159 [`move_iter`](../std/vec/trait.OwnedVector.html#tymethod.move_iter) which yields
160 `int` while consuming the `values` vector.)
161
162 # Type system
163
164 ## How do I store a function in a struct?
165
166 ~~~
167 struct Foo {
168     myfunc: fn(int, uint) -> i32
169 }
170
171 struct FooClosure<'a> {
172     myfunc: |int, uint|: 'a -> i32
173 }
174
175 fn a(a: int, b: uint) -> i32 {
176     (a as uint + b) as i32
177 }
178
179 fn main() {
180     let f = Foo { myfunc: a };
181     let g = FooClosure { myfunc: |a, b|  { (a - b as int) as i32 } };
182     println!("{}", (f.myfunc)(1, 2));
183     println!("{}", (g.myfunc)(3, 4));
184 }
185 ~~~
186
187 Note that the parenthesis surrounding `f.myfunc` are necessary: they are how Rust disambiguates field lookup and method call. The `'a` on `FooClosure` is the lifetime of the closure's environment pointer.
188
189 ## How do I express phantom types?
190
191 [Phantom types](http://www.haskell.org/haskellwiki/Phantom_type) are those that cannot be constructed at compile time. To express these in Rust, zero-variant `enum`s can be used:
192
193 ~~~
194 enum Open {}
195 enum Closed {}
196 ~~~
197
198 Phantom types are useful for enforcing state at compile time. For example:
199
200 ~~~
201 struct Door<State>(String);
202
203 struct Open;
204 struct Closed;
205
206 fn close(Door(name): Door<Open>) -> Door<Closed> {
207     Door::<Closed>(name)
208 }
209
210 fn open(Door(name): Door<Closed>) -> Door<Open> {
211     Door::<Open>(name)
212 }
213
214 let _ = close(Door::<Open>("front".to_string()));
215 ~~~
216
217 Attempting to close a closed door is prevented statically:
218
219 ~~~ {.ignore}
220 let _ = close(Door::<Closed>("front".to_string())); // error: mismatched types: expected `main::Door<main::Open>` but found `main::Door<main::Closed>`
221 ~~~
222
223 # FFI (Foreign Function Interface)
224
225 ## C function signature conversions
226
227 | Description         | C signature                                   | Equivalent Rust signature                      |
228 |---------------------|-----------------------------------------------|------------------------------------------------|
229 | no parameters       | `void foo(void);`                             | `fn foo();`                                    |
230 | return value        | `int foo(void);`                              | `fn foo() -> c_int;`                           |
231 | function parameters | `void foo(int x, int y);`                     | `fn foo(x: c_int, y: c_int);`                  |
232 | in-out pointers     | `void foo(const int* in_ptr, int* out_ptr);`  | `fn foo(in_ptr: *c_int, out_ptr: *mut c_int);` |
233
234 Note: The Rust signatures should be wrapped in an `extern "ABI" { ... }` block.
235
236 ### Representing opaque handles
237
238 You might see things like this in C APIs:
239
240 ~~~ {.notrust}
241 typedef struct Window Window;
242 Window* createWindow(int width, int height);
243 ~~~
244
245 You can use a zero-element `enum` ([phantom type](#how-do-i-express-phantom-types)) to represent the opaque object handle. The FFI would look like this:
246
247 ~~~ {.ignore}
248 enum Window {}
249 extern "C" {
250     fn createWindow(width: c_int, height: c_int) -> *Window;
251 }
252 ~~~
253
254 Using a phantom type ensures that the handles cannot be (safely) constructed in client code.
255
256 # Contributing to this page
257
258 For small examples, have full type annotations, as much as is reasonable, to keep it clear what, exactly, everything is doing. Try to link to the API docs, as well.
259
260 Similar documents for other programming languages:
261
262   * [http://pleac.sourceforge.net/](http://pleac.sourceforge.net)