Skip to content
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

Lots of doc cleanups ++ #11398

Closed
wants to merge 14 commits into from
1 change: 1 addition & 0 deletions Makefile.in
Original file line number Diff line number Diff line change
Expand Up @@ -410,6 +410,7 @@ export CFG_SRC_DIR
export CFG_BUILD_DIR
export CFG_VERSION
export CFG_VERSION_WIN
export CFG_RELEASE
export CFG_BUILD
export CFG_LLVM_ROOT
export CFG_ENABLE_MINGW_CROSS
Expand Down
1 change: 1 addition & 0 deletions configure
Original file line number Diff line number Diff line change
Expand Up @@ -806,6 +806,7 @@ do
make_dir $h/test/doc-guide-container
make_dir $h/test/doc-guide-tasks
make_dir $h/test/doc-guide-conditions
make_dir $h/test/doc-complement-cheatsheet
make_dir $h/test/doc-rust
done

Expand Down
81 changes: 46 additions & 35 deletions doc/complement-cheatsheet.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,113 +6,116 @@

Use [`ToStr`](http://static.rust-lang.org/doc/master/std/to_str/trait.ToStr.html).

```rust
~~~
let x: int = 42;
let y: ~str = x.to_str();
```
~~~

**String to int**

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).

```rust
~~~
let x: Option<int> = from_str("42");
let y: int = x.unwrap();
```
~~~

**Int to string, in non-base-10**

Use [`ToStrRadix`](http://static.rust-lang.org/doc/master/std/num/trait.ToStrRadix.html).

```rust
~~~
use std::num::ToStrRadix;

let x: int = 42;
let y: ~str = x.to_str_radix(16);
```
~~~

**String to int, in non-base-10**

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).

```rust
~~~
use std::num::from_str_radix;

let x: Option<int> = from_str_radix("deadbeef", 16);
let y: int = x.unwrap();
```
~~~

# File operations

## How do I read from a file?

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.

```rust
~~~ {.xfail-test}
use std::path::Path;
use std::io::fs::File;

let path : Path = Path::new("Doc-FAQ-Cheatsheet.md");
let on_error = || fail!("open of {:?} failed", path);
let reader : File = File::open(&path).unwrap_or_else(on_error);
```
~~~

## How do I iterate over the lines in a file?

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).

```rust
~~~
use std::io::buffered::BufferedReader;
# use std::io::mem::MemReader;

# let reader = MemReader::new(~[]);

let mut reader = BufferedReader::new(reader);
for line in reader.lines() {
print!("line: {}", line);
}
```
~~~

# String operations

## How do I search for a substring?

Use the [`find_str`](http://static.rust-lang.org/doc/master/std/str/trait.StrSlice.html#tymethod.find_str) method.

```rust
~~~
let str = "Hello, this is some random string";
let index: Option<uint> = str.find_str("rand");
```
~~~

# Containers

## How do I get the length of a vector?

The [`Container`](http://static.rust-lang.org/doc/master/std/container/trait.Container.html) trait provides the `len` method.

```rust
~~~
let u: ~[u32] = ~[0, 1, 2];
let v: &[u32] = &[0, 1, 2, 3];
let w: [u32, .. 5] = [0, 1, 2, 3, 4];

println!("u: {}, v: {}, w: {}", u.len(), v.len(), w.len()); // 3, 4, 5
```
~~~

## How do I iterate over a vector?

Use the [`iter`](http://static.rust-lang.org/doc/master/std/vec/trait.ImmutableVector.html#tymethod.iter) method.

```rust
~~~
let values: ~[int] = ~[1, 2, 3, 4, 5];
for value in values.iter() { // value: &int
println!("{}", *value);
}
```
~~~

(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.)

# Type system

## How do I store a function in a struct?

```rust
~~~
struct Foo {
myfunc: fn(int, uint) -> i32
}
Expand All @@ -131,24 +134,27 @@ fn main() {
println!("{}", (f.myfunc)(1, 2));
println!("{}", (g.myfunc)(3, 4));
}
```
~~~

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.

## How do I express phantom types?

[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:

```rust
~~~
enum Open {}
enum Closed {}
```
~~~

Phantom types are useful for enforcing state at compile time. For example:

```rust
~~~
struct Door<State>(~str);

struct Open;
struct Closed;

fn close(Door(name): Door<Open>) -> Door<Closed> {
Door::<Closed>(name)
}
Expand All @@ -157,40 +163,45 @@ fn open(Door(name): Door<Closed>) -> Door<Open> {
Door::<Open>(name)
}

let _ = close(Door::<Open>(~"front")); // ok
let _ = close(Door::<Open>(~"front"));
~~~

Attempting to close a closed door is prevented statically:

~~~ {.xfail-test}
let _ = close(Door::<Closed>(~"front")); // error: mismatched types: expected `main::Door<main::Open>` but found `main::Door<main::Closed>`
```
~~~

# FFI (Foreign Function Interface)

## C function signature conversions

Description | C signature | Equivalent Rust signature
----------------------|----------------------------------------------|------------------------------------------
no parameters | `void foo(void);` | `fn foo();`
return value | `int foo(void);` | `fn foo() -> c_int;`
function parameters | `void foo(int x, int y);` | `fn foo(x: int, y: int);`
in-out pointers | `void foo(const int* in_ptr, int* out_ptr);` | `fn foo(in_ptr: *c_int, out_ptr: *mut c_int);`
Description C signature Equivalent Rust signature
---------------------- ---------------------------------------------- ------------------------------------------
no parameters `void foo(void);` `fn foo();`
return value `int foo(void);` `fn foo() -> c_int;`
function parameters `void foo(int x, int y);` `fn foo(x: int, y: int);`
in-out pointers `void foo(const int* in_ptr, int* out_ptr);` `fn foo(in_ptr: *c_int, out_ptr: *mut c_int);`

Note: The Rust signatures should be wrapped in an `extern "ABI" { ... }` block.

### Representing opaque handles

You might see things like this in C APIs:

```c
~~~ {.notrust}
typedef struct Window Window;
Window* createWindow(int width, int height);
```
~~~

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:

```rust
~~~ {.xfail-test}
enum Window {}
extern "C" {
fn createWindow(width: c_int, height: c_int) -> *Window;
}
```
~~~

Using a phantom type ensures that the handles cannot be (safely) constructed in client code.

Expand Down
12 changes: 6 additions & 6 deletions doc/complement-lang-faq.md
Original file line number Diff line number Diff line change
Expand Up @@ -218,13 +218,13 @@ They start small (ideally in the hundreds of bytes) and expand dynamically by ca
* Managed boxes may not be shared between tasks
* Owned boxes may be transferred (moved) between tasks

## What is the difference between a borrowed pointer (`&`) and managed and owned boxes?
## What is the difference between a reference (`&`) and managed and owned boxes?

* Borrowed pointers point to the interior of a stack _or_ heap allocation
* Borrowed pointers can only be formed when it will provably be outlived by the referent
* Borrowed pointers to managed box pointers keep the managed boxes alive
* Borrowed pointers to owned boxes prevent their ownership from being transferred
* Borrowed pointers employ region-based alias analysis to ensure correctness
* References point to the interior of a stack _or_ heap allocation
* References can only be formed when it will provably be outlived by the referent
* References to managed box pointers keep the managed boxes alive
* References to owned boxes prevent their ownership from being transferred
* References employ region-based alias analysis to ensure correctness

## Why aren't function signatures inferred? Why only local slots?

Expand Down
2 changes: 1 addition & 1 deletion doc/guide-conditions.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
% Rust Condition and Error-handling Guide
% The Rust Condition and Error-handling Guide

# Introduction

Expand Down
2 changes: 1 addition & 1 deletion doc/guide-container.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
% Containers and Iterators Guide
% The Rust Containers and Iterators Guide

# Containers

Expand Down
4 changes: 2 additions & 2 deletions doc/guide-ffi.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
% Rust Foreign Function Interface Guide
% The Rust Foreign Function Interface Guide

# Introduction

Expand Down Expand Up @@ -417,7 +417,7 @@ However, there are currently no guarantees about the layout of an `enum`.

Rust's owned and managed boxes use non-nullable pointers as handles which point to the contained
object. However, they should not be manually created because they are managed by internal
allocators. Borrowed pointers can safely be assumed to be non-nullable pointers directly to the
allocators. References can safely be assumed to be non-nullable pointers directly to the
type. However, breaking the borrow checking or mutability rules is not guaranteed to be safe, so
prefer using raw pointers (`*`) if that's needed because the compiler can't make as many assumptions
about them.
Expand Down
Loading