Update Examples
parent
46243a69fc
commit
b01ccc1a85
89
Examples.md
89
Examples.md
@ -280,9 +280,9 @@ struct Rectangle
|
||||
|
||||
|
||||
|
||||
fn main()
|
||||
fn main
|
||||
// Create struct with field init shorthand
|
||||
let name = s"Peter" // note s-string
|
||||
let name = s"Peter" //! Note s-string
|
||||
age = 27
|
||||
peter = Person name, age
|
||||
|
||||
@ -383,7 +383,7 @@ enum WebEvent
|
||||
x, y: i64
|
||||
|
||||
fn inspect(event: WebEvent)
|
||||
match event // Note variant auto-import
|
||||
match event //! Note variant auto-import
|
||||
PageLoad => println! "page loaded"
|
||||
PageUnload => println! "page unloaded"
|
||||
// Destructure `c` from inside the `enum` variant.
|
||||
@ -397,7 +397,7 @@ fn inspect(event: WebEvent)
|
||||
|
||||
|
||||
|
||||
fn main()
|
||||
fn main
|
||||
let pressed = WebEvent::KeyPress 'x'
|
||||
pasted = WebEvent::Paste s"my text"
|
||||
click = WebEvent::Click x: 20, y: 80
|
||||
@ -423,10 +423,91 @@ fn main()
|
||||
<td>
|
||||
|
||||
```
|
||||
use crate::List::*;
|
||||
|
||||
enum List {
|
||||
Cons(u32, Box<List>),
|
||||
Nil,
|
||||
}
|
||||
|
||||
impl List {
|
||||
fn new() -> List {
|
||||
Nil
|
||||
}
|
||||
|
||||
fn prepend(self, elem: u32) -> List {
|
||||
Cons(elem, Box::new(self))
|
||||
}
|
||||
|
||||
fn len(&self) -> u32 {
|
||||
match self {
|
||||
Cons(_, tail) => 1 + tail.len(),
|
||||
Nil => 0
|
||||
}
|
||||
}
|
||||
|
||||
fn stringify(&self) -> String {
|
||||
match self {
|
||||
Cons(head, tail) => {
|
||||
format!("{}, {}", head, tail.stringify())
|
||||
},
|
||||
Nil => {
|
||||
format!("Nil")
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let mut list = List::new();
|
||||
|
||||
list = list.prepend(1);
|
||||
list = list.prepend(2);
|
||||
list = list.prepend(3);
|
||||
|
||||
println!("linked list has length: {}", list.len());
|
||||
println!("{}", list.stringify());
|
||||
}
|
||||
```
|
||||
</td><td>
|
||||
|
||||
```
|
||||
// use crate::List::*; //! Unneeded bc of match auto-import
|
||||
|
||||
enum List
|
||||
Cons(u32, Box<List>)
|
||||
Nil
|
||||
|
||||
impl List
|
||||
fn new -> List Nil
|
||||
|
||||
fn prepend(self, elem: u32) -> List
|
||||
Cons elem, Box::new self
|
||||
|
||||
fn len(&self) -> u32
|
||||
match self
|
||||
Cons _, tail => 1 + tail.len()
|
||||
Nil => 0
|
||||
|
||||
fn stringify(&self) -> String
|
||||
match self
|
||||
Cons head, tail =>
|
||||
format! "{}, {}", head, tail.stringify()
|
||||
Nil =>
|
||||
format! "Nil"
|
||||
|
||||
|
||||
|
||||
fn main
|
||||
let mut list = List::new()
|
||||
|
||||
list = list.prepend(1)
|
||||
.prepend(2)
|
||||
.prepend(3)
|
||||
|
||||
println! "linked list has length: {}", list.len()
|
||||
println! "{}", list.stringify()
|
||||
|
||||
```
|
||||
</td></tr></table>
|
||||
|
||||
|
Loading…
Reference in New Issue
Block a user