|
|
|
@ -3,12 +3,10 @@
|
|
|
|
|
x: i32,
|
|
|
|
|
y: i32,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
let origin: Point = Point { x: 0, y: 0 };
|
|
|
|
|
|
|
|
|
|
// A struct with unnamed fields, called a ‘tuple struct’
|
|
|
|
|
struct Point2(i32, i32);
|
|
|
|
|
|
|
|
|
|
let origin2 = Point2(0, 0);
|
|
|
|
|
|
|
|
|
|
// Basic C-like enum
|
|
|
|
@ -18,7 +16,6 @@
|
|
|
|
|
Up,
|
|
|
|
|
Down,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
let up = Direction::Up;
|
|
|
|
|
|
|
|
|
|
// Enum with fields
|
|
|
|
@ -26,14 +23,12 @@
|
|
|
|
|
AnI32(i32),
|
|
|
|
|
Nothing,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
let two: OptionalI32 = OptionalI32::AnI32(2);
|
|
|
|
|
let nothing = OptionalI32::Nothing;
|
|
|
|
|
|
|
|
|
|
// Generics //
|
|
|
|
|
|
|
|
|
|
struct Foo<T> { bar: T }
|
|
|
|
|
|
|
|
|
|
//
|
|
|
|
|
// This is defined in the standard library as `Option`
|
|
|
|
|
enum Optional<T> {
|
|
|
|
|
SomeVal(T),
|
|
|
|
@ -41,7 +36,6 @@
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Methods //
|
|
|
|
|
|
|
|
|
|
impl<T> Foo<T> {
|
|
|
|
|
// Instance methods take an explicit `self` parameter.
|
|
|
|
|
// Using `self` on its own will consume the caller, while
|
|
|
|
@ -50,7 +44,6 @@
|
|
|
|
|
fn get_bar(self) -> T {
|
|
|
|
|
self.bar
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Static methods don't take a `self` parameter, but can still
|
|
|
|
|
// use the generic `T` type.
|
|
|
|
|
fn do_baz(msg: &str, baz: T) -> T {
|
|
|
|
@ -58,7 +51,6 @@
|
|
|
|
|
baz
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Here `T` is inferred to be some integer type
|
|
|
|
|
let a_foo = Foo { bar: 1 };
|
|
|
|
|
println!("{}", a_foo.get_bar()); // 1
|
|
|
|
@ -68,16 +60,13 @@
|
|
|
|
|
let result: i32 = Foo::<i32>::do_baz("Hello", 24);
|
|
|
|
|
|
|
|
|
|
// Traits (known as interfaces or typeclasses in other languages) //
|
|
|
|
|
|
|
|
|
|
trait Frobnicate<T> {
|
|
|
|
|
fn frobnicate(self) -> Option<T>;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
impl<T> Frobnicate<T> for Foo<T> {
|
|
|
|
|
fn frobnicate(self) -> Option<T> {
|
|
|
|
|
Some(self.bar)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
let another_foo = Foo { bar: 1 };
|
|
|
|
|
println!("{:?}", another_foo.frobnicate()); // Some(1)
|
|
|
|
|