File tree 1 file changed +42
-0
lines changed
1 file changed +42
-0
lines changed Original file line number Diff line number Diff line change @@ -64,3 +64,45 @@ equality yet, but we’ll find out in the [`traits`][traits] section.
64
64
[ match ] : match.html
65
65
[ if-let ] : if-let.html
66
66
[ 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
You can’t perform that action at this time.
0 commit comments