Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions 14/14-7_newtype_1.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
struct Years(i64);

struct Days(i64);

impl Years {
pub fn to_days(&self) -> Days {
Days(self.0 * 365)
}
}


impl Days {
/// truncates partial years
pub fn to_years(&self) -> Years {
Years(self.0 / 365)
}
}

fn old_enough(age: &Years) -> bool {
age.0 >= 18
}

fn main() {
// let age = Years(5);
let age = Years(18);
let age_days = age.to_days();
println!("Old enough {}", old_enough(&age));
println!("Old enough {}", old_enough(&age_days.to_years()));
// println!("Old enough {}", old_enough(&age_days));
}
7 changes: 7 additions & 0 deletions 14/14-7_newtype_2.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
struct Years(i64);

fn main() {
let years = Years(42);
let years_as_primitive_1: i64 = years.0; // Tuple
let Years(years_as_primitive_2) = years; // Destructuring
}
58 changes: 58 additions & 0 deletions 14/14-8-2_associated_types.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
struct Container(i32, i32);

// A trait which checks if 2 items are stored inside of container.
// Also retrieves first or last value.
// 2つの要素がコンテナ型の中に保持されていることを確認するトレイト。
// また、最初あるいは最後の要素を取り出すこともできる。
trait Contains {
// Define generic types here which methods will be able to utilize.
// メソッドが使用できるジェネリック型を定義
type A;
type B;

fn contains(&self, _: &Self::A, _: &Self::B) -> bool;
fn first(&self) -> i32;
fn last(&self) -> i32;
}

impl Contains for Container {
// Specify what types `A` and `B` are. If the `input` type
// is `Container(i32, i32)`, the `output` types are determined
// as `i32` and `i32`.
// `A`と`B`がどの型であるかを明示。インプットの型(訳注: つまり`Self`の型)
// が`Container(i32, i32)`である場合、出力型は`i32`と`i32`となる。
type A = i32;
type B = i32;

// `&Self::A` and `&Self::B` are also valid here.
// `&i32`の代わりに`&Self::A`または`&self::B`と書いても良い
fn contains(&self, number_1: &i32, number_2: &i32) -> bool {
(&self.0 == number_1) && (&self.1 == number_2)
}
// Grab the first number.
// 1つ目の数を取得
fn first(&self) -> i32 { self.0 }

// Grab the last number.
// 最後の数を取得
fn last(&self) -> i32 { self.1 }
}

fn difference<C: Contains>(container: &C) -> i32 {
container.last() - container.first()
}

fn main() {
let number_1 = 3;
let number_2 = 10;

let container = Container(number_1, number_2);

println!("Does container contain {} and {}: {}",
&number_1, &number_2,
container.contains(&number_1, &number_2));
println!("First number: {}", container.first());
println!("Last number: {}", container.last());

println!("The difference is: {}", difference(&container));
}