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