Rust : Update.
This commit is contained in:
parent
2fc2ae5e5e
commit
7c000e05a2
15
dev/lang/rust/Error.md
Normal file
15
dev/lang/rust/Error.md
Normal file
|
@ -0,0 +1,15 @@
|
|||
# Error.
|
||||
|
||||
Replaces `Option<T>`.
|
||||
|
||||
# Create.
|
||||
|
||||
```rust
|
||||
fn foo() -> Result<String, String> {
|
||||
if bar {
|
||||
Err("Barrr!")
|
||||
} else {
|
||||
Ok("Foo!")
|
||||
}
|
||||
}
|
||||
```
|
37
dev/lang/rust/Generics.md
Normal file
37
dev/lang/rust/Generics.md
Normal file
|
@ -0,0 +1,37 @@
|
|||
# Rust generics.
|
||||
|
||||
Generics in rust are similar to java's.
|
||||
|
||||
# Definition.
|
||||
|
||||
Function:
|
||||
|
||||
```rust
|
||||
fn largest<T>(list: &[T]) -> &T {}
|
||||
```
|
||||
|
||||
Struct:
|
||||
|
||||
```rust
|
||||
struct Point<T> {
|
||||
x: T,
|
||||
y: T,
|
||||
}
|
||||
|
||||
impl<T> Point<T> {
|
||||
fn x(&self) -> &T {
|
||||
&self.x
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Enum:
|
||||
|
||||
```rust
|
||||
enum Result<T, E> {
|
||||
Ok(T),
|
||||
Err(E),
|
||||
}
|
||||
```
|
||||
|
||||
|
59
dev/lang/rust/Option.md
Normal file
59
dev/lang/rust/Option.md
Normal file
|
@ -0,0 +1,59 @@
|
|||
# Option.
|
||||
|
||||
# Definition.
|
||||
|
||||
```rust
|
||||
enum Option<T> {
|
||||
None,
|
||||
Some(T),
|
||||
}
|
||||
```
|
||||
|
||||
# Usage.
|
||||
|
||||
```rust
|
||||
fn maybe_icecream(hour: u16) -> Option<u16> {
|
||||
if hour > 10 { Some(5) }
|
||||
else { None }
|
||||
}
|
||||
```
|
||||
|
||||
# Subtypes.
|
||||
|
||||
## If-let.
|
||||
|
||||
```rust
|
||||
let letter: Option<i32> = Some(12);
|
||||
if let Some(i) = letter {
|
||||
// It was Some().
|
||||
} else {
|
||||
// It was None.
|
||||
}
|
||||
```
|
||||
|
||||
## While-let.
|
||||
|
||||
```rust
|
||||
let letter: Option<i32> = Some(0);
|
||||
while let Some(i) = letter {
|
||||
if i > 9 {
|
||||
foo();
|
||||
letter = None;
|
||||
} else {
|
||||
bar()
|
||||
letter = Some(i + 1);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Match.
|
||||
|
||||
Use `ref` keyword to borrow value that doesn't implement `Copy` trait.
|
||||
|
||||
```rust
|
||||
let y: Option<Point> = Some(Point { x: 100, y: 200 });
|
||||
match y {
|
||||
Some(ref p) => println!("Co-ordinates are {},{} ", p.x, p.y),
|
||||
_ => panic!("no match!"),
|
||||
}
|
||||
```
|
Loading…
Reference in a new issue