Skip to content

Commit b242a86

Browse files
committed
Mention that enum constructors are functions
Fixes #25850
1 parent 7b0f2af commit b242a86

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

src/doc/trpl/enums.md

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,3 +64,45 @@ equality yet, but we’ll find out in the [`traits`][traits] section.
6464
[match]: match.html
6565
[if-let]: if-let.html
6666
[traits]: traits.html
67+
68+
# Constructors as functions
69+
70+
An enum’s constructors can also be used like functions. For example:
71+
72+
```rust
73+
# enum Message {
74+
# Write(String),
75+
# }
76+
let m = Message::Write("Hello, world".to_string());
77+
```
78+
79+
Is the same as
80+
81+
```rust
82+
# enum Message {
83+
# Write(String),
84+
# }
85+
fn foo(x: String) -> Message {
86+
Message::Write(x)
87+
}
88+
89+
let x = foo("Hello, world".to_string());
90+
```
91+
92+
This is not immediately useful to us, but when we get to
93+
[`closures`][closures], we’ll talk about passing functions as arguments to
94+
other functions. For example, with [`iterators`][iterators], we can do this
95+
to convert a vector of `String`s into a vector of `Message::Write`s:
96+
97+
```rust
98+
# enum Message {
99+
# Write(String),
100+
# }
101+
102+
let v = vec!["Hello".to_string(), "World".to_string()];
103+
104+
let v1: Vec<Message> = v.into_iter().map(Message::Write).collect();
105+
```
106+
107+
[closures]: closures.html
108+
[iterators]: iterators.html

0 commit comments

Comments
 (0)