Skip to content

Mention that enum constructors are functions #26142

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

Merged
merged 1 commit into from
Jun 10, 2015
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions src/doc/trpl/enums.md
Original file line number Diff line number Diff line change
Expand Up @@ -64,3 +64,45 @@ equality yet, but we’ll find out in the [`traits`][traits] section.
[match]: match.html
[if-let]: if-let.html
[traits]: traits.html

# Constructors as functions

An enum’s constructors can also be used like functions. For example:

```rust
# enum Message {
# Write(String),
# }
let m = Message::Write("Hello, world".to_string());
```

Is the same as

```rust
# enum Message {
# Write(String),
# }
fn foo(x: String) -> Message {
Message::Write(x)
}

let x = foo("Hello, world".to_string());
```

This is not immediately useful to us, but when we get to
[`closures`][closures], we’ll talk about passing functions as arguments to
other functions. For example, with [`iterators`][iterators], we can do this
to convert a vector of `String`s into a vector of `Message::Write`s:

```rust
# enum Message {
# Write(String),
# }

let v = vec!["Hello".to_string(), "World".to_string()];

let v1: Vec<Message> = v.into_iter().map(Message::Write).collect();
```

[closures]: closures.html
[iterators]: iterators.html