Skip to content

Commit 65a1287

Browse files
committed
Discuss the Option type a bit in the tutorial
as per #3577
1 parent 01c0971 commit 65a1287

File tree

1 file changed

+19
-4
lines changed

1 file changed

+19
-4
lines changed

doc/tutorial.md

Lines changed: 19 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1817,14 +1817,29 @@ struct Stack<T> {
18171817
elements: ~[mut T]
18181818
}
18191819
1820-
enum Maybe<T> {
1821-
Just(T),
1822-
Nothing
1820+
enum Option<T> {
1821+
Some(T),
1822+
None
18231823
}
18241824
~~~~
18251825

18261826
These declarations can be instantiated to valid types like `Set<int>`,
1827-
`Stack<int>` and `Maybe<int>`.
1827+
`Stack<int>` and `Option<int>`.
1828+
1829+
The last type in that example, `Option`, appears frequently in Rust code.
1830+
Because Rust does not have null pointers (except in unsafe code), we need
1831+
another way to write a function whose result isn't defined on every possible
1832+
combination of arguments of the appropriate types. The usual way is to write
1833+
a function that returns `Option<T>` instead of `T`.
1834+
1835+
~~~~
1836+
fn radius(shape: Shape) -> Option<float> {
1837+
match shape {
1838+
Circle(_, radius) => Some(radius),
1839+
Rectangle(*) => None
1840+
}
1841+
}
1842+
~~~~
18281843

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

0 commit comments

Comments
 (0)