Skip to content

Commit

Permalink
Discuss the Option type a bit in the tutorial
Browse files Browse the repository at this point in the history
  • Loading branch information
catamorphism committed Dec 11, 2012
1 parent 86f7eb3 commit 7698427
Showing 1 changed file with 19 additions and 4 deletions.
23 changes: 19 additions & 4 deletions doc/tutorial.md
Original file line number Diff line number Diff line change
Expand Up @@ -1817,14 +1817,29 @@ struct Stack<T> {
elements: ~[mut T]
}
enum Maybe<T> {
Just(T),
Nothing
enum Option<T> {
Some(T),
None
}
~~~~

These declarations can be instantiated to valid types like `Set<int>`,
`Stack<int>` and `Maybe<int>`.
`Stack<int>` and `Option<int>`.

The last type in that example, `Option`, appears frequently in Rust code.
Because Rust does not have null pointers (except in unsafe code), we need
another way to write a function whose result isn't defined on every possible
combination of arguments of the appropriate types. The usual way is to write
a function that returns `Option<T>` instead of `T`.

~~~~
fn radius(shape: Shape) -> Option<float> {
match shape {
Circle(_, radius) => Some(radius),
Rectangle(*) => None
}
}
~~~~

The Rust compiler compiles generic functions very efficiently by
*monomorphizing* them. *Monomorphization* is a fancy name for a simple
Expand Down

0 comments on commit 7698427

Please sign in to comment.