Use the [`iter`](std/slice/trait.ImmutableVector.html#tymethod.iter) method.
~~~
let values: Vec<int> = vec![1, 2, 3, 4, 5];
for value in values.iter() { // value: &int
println!("{}", *value);
}
~~~
(See also [`mut_iter`](std/slice/trait.MutableVector.html#tymethod.mut_iter)
which yields `&mut int` and
[`move_iter`](std/slice/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?
~~~
struct Foo {
myfunc: fn(int, uint) -> i32
}
struct FooClosure<'a> {
myfunc: |int, uint|: 'a -> i32
}
fn a(a: int, b: uint) -> i32 {
(a as uint + b) as i32
}
fn main() {
let f = Foo { myfunc: a };
let g = FooClosure { myfunc: |a, b| { (a - b as int) as i32 } };
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:
~~~
enum Open {}
enum Closed {}
~~~
Phantom types are useful for enforcing state at compile time. For example:
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
typedefstructWindowWindow;
Window*createWindow(intwidth,intheight);
~~~
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:
Using a phantom type ensures that the handles cannot be (safely) constructed in client code.
# 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.
Similar documents for other programming languages: