Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Tour of Rust #37

Merged
merged 3 commits into from
Sep 23, 2023
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
17 changes: 17 additions & 0 deletions tour-of-rust/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
### Generated by gibo (https://github.com/simonwhitaker/gibo)
### https://raw.github.com/github/gitignore/3bb7b4b767f3f8df07e362dfa03c8bd425f16d32/Rust.gitignore

# Generated by Cargo
# will have compiled files and executables
debug/
target/

# Remove Cargo.lock from gitignore if creating an executable, leave it for libraries
# More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html
Cargo.lock

# These are backup files generated by rustfmt
**/*.rs.bk

# MSVC Windows builds of rustc generate these, which store debugging information
*.pdb
8 changes: 8 additions & 0 deletions tour-of-rust/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
[package]
name = "tour-of-rust"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
3 changes: 3 additions & 0 deletions tour-of-rust/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# Tour of Rust

https://tourofrust.com
9 changes: 9 additions & 0 deletions tour-of-rust/examples/06_ja.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
fn main() {
let a = 13u8;
let b = 7u32;
let c = a as u32 + b;
println!("{}", c);

let t = true;
println!("{}", t as u8);
}
6 changes: 6 additions & 0 deletions tour-of-rust/examples/08_ja.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
/// 配列
fn main() {
let nums: [i32; 3] = [1, 2, 3];
println!("{:?}", nums);
println!("{}", nums[1]);
}
22 changes: 22 additions & 0 deletions tour-of-rust/examples/100_ja.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
use std::rc::Rc;

struct Pie;

impl Pie {
fn eat(&self) {
println!("tastes better on the heap!")
}
}

fn main() {
let heap_pie = Rc::new(Pie);
let heap_pie2 = heap_pie.clone();
let heap_pie3 = heap_pie2.clone();

heap_pie3.eat();
heap_pie2.eat();
heap_pie.eat();

// all reference count smart pointers are dropped now
// the heap data Pie finally deallocates
}
18 changes: 18 additions & 0 deletions tour-of-rust/examples/11_ja.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
fn make_nothing() -> () {
return ();
}

// 戻り値は () と推論
fn make_nothing2() {
// この関数は戻り値が指定されないため () を返す
}

fn main() {
let a = make_nothing();
let b = make_nothing2();

// 空を表示するのは難しいので、
// a と b のデバッグ文字列を表示
println!("a の値: {:?}", a);
println!("b の値: {:?}", b);
}
25 changes: 25 additions & 0 deletions tour-of-rust/examples/18_ja.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
fn main() {
let x = 42;

match x {
0 => {
println!("found zero");
}
// 複数の値にマッチ
1 | 2 => {
println!("found 1 or 2!");
}
// 範囲にマッチ
3..=9 => {
println!("found a number 3 to 9 inclusively");
}
// マッチした数字を変数に束縛
matched_num @ 10..=100 => {
println!("found {} number between 10 to 100!", matched_num);
}
// どのパターンにもマッチしない場合のデフォルトマッチが必須
_ => {
println!("found something else!");
}
}
}
38 changes: 38 additions & 0 deletions tour-of-rust/examples/26_ja.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
/// メモリの中でデータを作成する
struct SeaCreature {
animal_type: String,
name: String,
arms: i32,
legs: i32,
weapon: String,
}

fn main() {
// SeaCreatureのデータはスタックに入ります。
let ferris = SeaCreature {
// String構造体もスタックに入りますが、
// ヒープに入るデータの参照アドレスが一つ入ります。
animal_type: String::from("crab"),
name: String::from("Ferris"),
arms: 2,
legs: 4,
weapon: String::from("claw"),
};

let sarah = SeaCreature {
animal_type: String::from("octopus"),
name: String::from("Sarah"),
arms: 8,
legs: 0,
weapon: String::from("none"),
};

println!(
"{} is a {}. They have {} arms, {} legs, and a {} weapon",
ferris.name, ferris.animal_type, ferris.arms, ferris.legs, ferris.weapon
);
println!(
"{} is a {}. They have {} arms, and {} legs. They have no weapon..",
sarah.name, sarah.animal_type, sarah.arms, sarah.legs
);
}
60 changes: 60 additions & 0 deletions tour-of-rust/examples/30_ja.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
#![allow(dead_code)] // この行でコンパイラのwaringsメッセージを止めます。

enum Species {
Crab,
Octopus,
Fish,
Clam,
}
enum PoisonType {
Acidic,
Painful,
Lethal,
}
enum Size {
Big,
Small,
}
enum Weapon {
Claw(i32, Size),
Poison(PoisonType),
None,
}

struct SeaCreature {
species: Species,
name: String,
arms: i32,
legs: i32,
weapon: Weapon,
}

fn main() {
// SeaCreatureのデータはスタックに入ります。
let ferris = SeaCreature {
// String構造体もスタックに入りますが、
// ヒープに入るデータの参照アドレスが一つ入ります。
species: Species::Crab,
name: String::from("Ferris"),
arms: 2,
legs: 4,
weapon: Weapon::Claw(2, Size::Small),
};

match ferris.species {
Species::Crab => match ferris.weapon {
Weapon::Claw(num_claws, size) => {
let size_description = match size {
Size::Big => "big",
Size::Small => "small",
};
println!(
"ferris is a crab with {} {} claws",
num_claws, size_description
)
}
_ => println!("ferris is a crab with some other weapon"),
},
_ => println!("ferris is some other animal"),
}
}
24 changes: 24 additions & 0 deletions tour-of-rust/examples/33_ja.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
// 部分的に定義された構造体型
struct BagOfHolding<T> {
item: T,
}

fn main() {
// 注意: ジェネリック型を使用すると、型はコンパイル時に作成される。
// ::<> (turbofish) で明示的に型を指定
let i32_bag = BagOfHolding::<i32> { item: 42 };
let bool_bag = BagOfHolding::<bool> { item: true };

// ジェネリック型でも型推論可能
let float_bag = BagOfHolding { item: 3.14 };

// 注意: 実生活では手提げ袋を手提げ袋に入れないように
let bag_in_bag = BagOfHolding {
item: BagOfHolding { item: "boom!" },
};

println!(
"{} {} {} {}",
i32_bag.item, bool_bag.item, float_bag.item, bag_in_bag.item.item
);
}
35 changes: 35 additions & 0 deletions tour-of-rust/examples/35_ja.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
/// Option

// 部分的に定義された構造体型
struct BagOfHolding<T> {
// パラメータ T を渡すことが可能
item: Option<T>,
}

fn main() {
// 注意: i32 が入るバッグに、何も入っていません!
// None からは型が決められないため、型を指定する必要があります。
let i32_bag = BagOfHolding::<i32> { item: None };

if i32_bag.item.is_none() {
println!("バッグには何もない!")
} else {
println!("バッグには何かある!")
}

let i32_bag = BagOfHolding::<i32> { item: Some(42) };

if i32_bag.item.is_some() {
println!("バッグには何かある!")
} else {
println!("バッグには何もない!")
}

// match は Option をエレガントに分解して、
// すべてのケースが処理されることを保証できます!
match i32_bag.item {
Some(v) => println!("バッグに {} を発見!", v),
None => println!("何も見付からなかった"),
}
}
18 changes: 18 additions & 0 deletions tour-of-rust/examples/36_ja.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
fn do_something_that_might_fail(i: i32) -> Result<f32, String> {
if i == 42 {
Ok(13.0)
} else {
Err(String::from("正しい値ではありません"))
}
}

fn main() {
let result = do_something_that_might_fail(12);

// match は Result をエレガントに分解して、
// すべてのケースが処理されることを保証できます!
match result {
Ok(v) => println!("発見 {}", v),
Err(e) => println!("Error: {}", e),
}
}
14 changes: 14 additions & 0 deletions tour-of-rust/examples/38_ja.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
fn do_something_that_might_fail(i: i32) -> Result<f32, String> {
if i == 42 {
Ok(13.0)
} else {
Err(String::from("正しい値ではありません"))
}
}

fn main() -> Result<(), String> {
// コードが簡潔なのに注目!
let v = do_something_that_might_fail(42)?;
println!("発見 {}", v);
Ok(())
}
20 changes: 20 additions & 0 deletions tour-of-rust/examples/40_ja.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
fn main() {
// 型を明示的に指定
let mut i32_vec = Vec::<i32>::new(); // turbofish <3
i32_vec.push(1);
i32_vec.push(2);
i32_vec.push(3);

// もっと賢く、型を自動的に推論
let mut float_vec = Vec::new();
float_vec.push(1.3);
float_vec.push(2.3);
float_vec.push(3.4);

// きれいなマクロ!
let string_vec = vec![String::from("Hello"), String::from("World")];

for word in string_vec.iter() {
println!("{}", word);
}
}
19 changes: 19 additions & 0 deletions tour-of-rust/examples/46_ja.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
struct Foo {
x: i32,
}

fn do_something(f: Foo) {
println!("{}", f.x);
// f はここでドロップ
}

fn main() {
let foo = Foo { x: 42 };
// foo の所有権は do_something に移動
do_something(foo);

// foo は使えなくなる
// borrow of moved value: `foo`
// value borrowed here after move
// println!("{}", foo.x);
}
32 changes: 32 additions & 0 deletions tour-of-rust/examples/49_ja.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
/// 参照による所有権の可変な借用
struct Foo {
x: i32,
}

fn do_something(f: Foo) {
println!("{}", f.x);
// f はここでドロップ
}

fn main() {
let mut foo = Foo { x: 42 };
let f = &mut foo;

// 失敗: do_something(foo) はここでエラー
// foo は可変に借用されており移動できないため

// 失敗: foo.x = 13; はここでエラー
// foo は可変に借用されている間は変更できないため

f.x = 13;
// f はここから先では使用されないため、ここでドロップ

println!("{}", foo.x);

// 可変な借用はドロップされているため変更可能
foo.x = 7;

// foo の所有権を関数に移動
do_something(foo);
}
Loading