about summary refs log tree commit diff
diff options
context:
space:
mode:
authorSteve Klabnik <steve@steveklabnik.com>2015-06-09 16:12:43 -0400
committerSteve Klabnik <steve@steveklabnik.com>2015-06-09 16:12:45 -0400
commitb242a86864216e4d03bb1f5158afc2e9ffed9e21 (patch)
tree2456c16852433edb9b4e311ced2151a6413d645c
parent7b0f2af27f18b6c81fe6a2faab0ba96e0da3bba5 (diff)
downloadrust-b242a86864216e4d03bb1f5158afc2e9ffed9e21.tar.gz
rust-b242a86864216e4d03bb1f5158afc2e9ffed9e21.zip
Mention that enum constructors are functions
Fixes #25850
-rw-r--r--src/doc/trpl/enums.md42
1 files changed, 42 insertions, 0 deletions
diff --git a/src/doc/trpl/enums.md b/src/doc/trpl/enums.md
index 01905caf5ec..8ad4eeedd18 100644
--- a/src/doc/trpl/enums.md
+++ b/src/doc/trpl/enums.md
@@ -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