From e89c627772e40e33f17651dab337820bfca4653c Mon Sep 17 00:00:00 2001 From: Brendan Zabarauskas Date: Thu, 12 Dec 2013 15:32:50 -0800 Subject: [PATCH] Add phantom type docs --- Doc-FAQ-Cheatsheet.md | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/Doc-FAQ-Cheatsheet.md b/Doc-FAQ-Cheatsheet.md index 2dc2f32..abbda7c 100644 --- a/Doc-FAQ-Cheatsheet.md +++ b/Doc-FAQ-Cheatsheet.md @@ -106,6 +106,34 @@ for value in values.iter() { // value: &int (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 express phantom types in Rust? + +[Phantom types](http://www.haskell.org/haskellwiki/Phantom_type) are types 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(~str); + +fn close(Door(name): Door) -> Door { + Door(name) +} + +fn open(Door(name): Door) -> Door { + Door(name) +} + +close(Door::(~"front")) // ok +close(Door::(~"front")) // error: mismatched types: expected `main::Door` but found `main::Door` +~~~ + # Contributing to this page 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.