Skip to content

Commit 239347a

Browse files
committed
ch13 関数型言語の機能: イテレータとクロージャの和訳を最新版に更新
rust-lang/book@19c40bf
1 parent fcc533b commit 239347a

File tree

118 files changed

+1498
-2982
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

118 files changed

+1498
-2982
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
[package]
22
name = "minigrep"
33
version = "0.1.0"
4-
authors = ["Your Name <[email protected]>"]
5-
edition = "2018"
4+
edition = "2021"
65

76
[dependencies]

listings/ch13-functional-features/listing-12-23-reproduced/src/lib.rs

+12-14
Original file line numberDiff line numberDiff line change
@@ -4,42 +4,42 @@ use std::fs;
44

55
pub struct Config {
66
pub query: String,
7-
pub filename: String,
8-
pub case_sensitive: bool,
7+
pub file_path: String,
8+
pub ignore_case: bool,
99
}
1010

1111
// ANCHOR: ch13
1212
impl Config {
13-
pub fn new(args: &[String]) -> Result<Config, &'static str> {
13+
pub fn build(args: &[String]) -> Result<Config, &'static str> {
1414
if args.len() < 3 {
1515
return Err("not enough arguments");
1616
}
1717

1818
let query = args[1].clone();
19-
let filename = args[2].clone();
19+
let file_path = args[2].clone();
2020

21-
let case_sensitive = env::var("CASE_INSENSITIVE").is_err();
21+
let ignore_case = env::var("IGNORE_CASE").is_ok();
2222

2323
Ok(Config {
2424
query,
25-
filename,
26-
case_sensitive,
25+
file_path,
26+
ignore_case,
2727
})
2828
}
2929
}
3030
// ANCHOR_END: ch13
3131

3232
pub fn run(config: Config) -> Result<(), Box<dyn Error>> {
33-
let contents = fs::read_to_string(config.filename)?;
33+
let contents = fs::read_to_string(config.file_path)?;
3434

35-
let results = if config.case_sensitive {
36-
search(&config.query, &contents)
37-
} else {
35+
let results = if config.ignore_case {
3836
search_case_insensitive(&config.query, &contents)
37+
} else {
38+
search(&config.query, &contents)
3939
};
4040

4141
for line in results {
42-
println!("{}", line);
42+
println!("{line}");
4343
}
4444

4545
Ok(())
@@ -104,5 +104,3 @@ Trust me.";
104104
);
105105
}
106106
}
107-
108-
fn main() {}

listings/ch13-functional-features/listing-12-23-reproduced/src/main.rs

+3-4
Original file line numberDiff line numberDiff line change
@@ -6,14 +6,13 @@ use minigrep::Config;
66
fn main() {
77
let args: Vec<String> = env::args().collect();
88

9-
let config = Config::new(&args).unwrap_or_else(|err| {
10-
println!("Problem parsing arguments: {}", err);
9+
let config = Config::build(&args).unwrap_or_else(|err| {
10+
println!("Problem parsing arguments: {err}");
1111
process::exit(1);
1212
});
1313

1414
if let Err(e) = minigrep::run(config) {
15-
println!("Application error: {}", e);
16-
15+
println!("Application error: {e}");
1716
process::exit(1);
1817
}
1918
}
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
[package]
22
name = "minigrep"
33
version = "0.1.0"
4-
authors = ["Your Name <[email protected]>"]
5-
edition = "2018"
4+
edition = "2021"
65

76
[dependencies]

listings/ch13-functional-features/listing-12-24-reproduced/src/lib.rs

+12-12
Original file line numberDiff line numberDiff line change
@@ -4,40 +4,40 @@ use std::fs;
44

55
pub struct Config {
66
pub query: String,
7-
pub filename: String,
8-
pub case_sensitive: bool,
7+
pub file_path: String,
8+
pub ignore_case: bool,
99
}
1010

1111
impl Config {
12-
pub fn new(args: &[String]) -> Result<Config, &'static str> {
12+
pub fn build(args: &[String]) -> Result<Config, &'static str> {
1313
if args.len() < 3 {
1414
return Err("not enough arguments");
1515
}
1616

1717
let query = args[1].clone();
18-
let filename = args[2].clone();
18+
let file_path = args[2].clone();
1919

20-
let case_sensitive = env::var("CASE_INSENSITIVE").is_err();
20+
let ignore_case = env::var("IGNORE_CASE").is_ok();
2121

2222
Ok(Config {
2323
query,
24-
filename,
25-
case_sensitive,
24+
file_path,
25+
ignore_case,
2626
})
2727
}
2828
}
2929

3030
pub fn run(config: Config) -> Result<(), Box<dyn Error>> {
31-
let contents = fs::read_to_string(config.filename)?;
31+
let contents = fs::read_to_string(config.file_path)?;
3232

33-
let results = if config.case_sensitive {
34-
search(&config.query, &contents)
35-
} else {
33+
let results = if config.ignore_case {
3634
search_case_insensitive(&config.query, &contents)
35+
} else {
36+
search(&config.query, &contents)
3737
};
3838

3939
for line in results {
40-
println!("{}", line);
40+
println!("{line}");
4141
}
4242

4343
Ok(())

listings/ch13-functional-features/listing-12-24-reproduced/src/main.rs

+3-4
Original file line numberDiff line numberDiff line change
@@ -7,17 +7,16 @@ use minigrep::Config;
77
fn main() {
88
let args: Vec<String> = env::args().collect();
99

10-
let config = Config::new(&args).unwrap_or_else(|err| {
11-
eprintln!("Problem parsing arguments: {}", err);
10+
let config = Config::build(&args).unwrap_or_else(|err| {
11+
eprintln!("Problem parsing arguments: {err}");
1212
process::exit(1);
1313
});
1414

1515
// --snip--
1616
// ANCHOR_END: ch13
1717

1818
if let Err(e) = minigrep::run(config) {
19-
eprintln!("Application error: {}", e);
20-
19+
eprintln!("Application error: {e}");
2120
process::exit(1);
2221
}
2322
// ANCHOR: ch13

listings/ch13-functional-features/listing-13-01/Cargo.lock

+3-2
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
[package]
2-
name = "workout-app"
2+
name = "shirt-company"
33
version = "0.1.0"
4-
authors = ["Your Name <[email protected]>"]
5-
edition = "2018"
4+
edition = "2021"
65

76
[dependencies]
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
$ cargo run
2+
Compiling shirt-company v0.1.0 (file:///projects/shirt-company)
3+
Finished dev [unoptimized + debuginfo] target(s) in 0.27s
4+
Running `target/debug/shirt-company`
5+
The user with preference Some(Red) gets Red
6+
The user with preference None gets Blue
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,54 @@
1-
// ANCHOR: here
2-
use std::thread;
3-
use std::time::Duration;
1+
#[derive(Debug, PartialEq, Copy, Clone)]
2+
enum ShirtColor {
3+
Red,
4+
Blue,
5+
}
6+
7+
struct Inventory {
8+
shirts: Vec<ShirtColor>,
9+
}
10+
11+
impl Inventory {
12+
fn giveaway(&self, user_preference: Option<ShirtColor>) -> ShirtColor {
13+
user_preference.unwrap_or_else(|| self.most_stocked())
14+
}
415

5-
fn simulated_expensive_calculation(intensity: u32) -> u32 {
6-
println!("calculating slowly...");
7-
thread::sleep(Duration::from_secs(2));
8-
intensity
16+
fn most_stocked(&self) -> ShirtColor {
17+
let mut num_red = 0;
18+
let mut num_blue = 0;
19+
20+
for color in &self.shirts {
21+
match color {
22+
ShirtColor::Red => num_red += 1,
23+
ShirtColor::Blue => num_blue += 1,
24+
}
25+
}
26+
if num_red > num_blue {
27+
ShirtColor::Red
28+
} else {
29+
ShirtColor::Blue
30+
}
31+
}
932
}
10-
// ANCHOR_END: here
1133

12-
fn main() {}
34+
fn main() {
35+
let store = Inventory {
36+
shirts: vec![ShirtColor::Blue, ShirtColor::Red, ShirtColor::Blue],
37+
};
38+
39+
let user_pref1 = Some(ShirtColor::Red);
40+
let giveaway1 = store.giveaway(user_pref1);
41+
println!(
42+
// "好み{:?}を持つユーザは{:?}を得ます"
43+
"The user with preference {:?} gets {:?}",
44+
user_pref1, giveaway1
45+
);
46+
47+
let user_pref2 = None;
48+
let giveaway2 = store.giveaway(user_pref2);
49+
println!(
50+
// "好み{:?}を持つユーザは{:?}を得ます"
51+
"The user with preference {:?} gets {:?}",
52+
user_pref2, giveaway2
53+
);
54+
}
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
[package]
22
name = "workout-app"
33
version = "0.1.0"
4-
authors = ["Your Name <[email protected]>"]
5-
edition = "2018"
4+
edition = "2021"
65

76
[dependencies]

listings/ch13-functional-features/listing-13-02/src/main.rs

+22-8
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,33 @@
11
use std::thread;
22
use std::time::Duration;
33

4-
fn simulated_expensive_calculation(intensity: u32) -> u32 {
5-
println!("calculating slowly...");
6-
thread::sleep(Duration::from_secs(2));
7-
intensity
8-
}
4+
fn generate_workout(intensity: u32, random_number: u32) {
5+
// ANCHOR: here
6+
let expensive_closure = |num: u32| -> u32 {
7+
println!("calculating slowly...");
8+
thread::sleep(Duration::from_secs(2));
9+
num
10+
};
11+
// ANCHOR_END: here
912

10-
fn generate_workout(intensity: u32, random_number: u32) {}
13+
if intensity < 25 {
14+
println!("Today, do {} pushups!", expensive_closure(intensity));
15+
println!("Next, do {} situps!", expensive_closure(intensity));
16+
} else {
17+
if random_number == 3 {
18+
println!("Take a break today! Remember to stay hydrated!");
19+
} else {
20+
println!(
21+
"Today, run for {} minutes!",
22+
expensive_closure(intensity)
23+
);
24+
}
25+
}
26+
}
1127

12-
// ANCHOR: here
1328
fn main() {
1429
let simulated_user_specified_value = 10;
1530
let simulated_random_number = 7;
1631

1732
generate_workout(simulated_user_specified_value, simulated_random_number);
1833
}
19-
// ANCHOR_END: here

listings/ch13-functional-features/listing-13-03/Cargo.lock

+1-1
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
[package]
2-
name = "workout-app"
2+
name = "closure-example"
33
version = "0.1.0"
4-
authors = ["Your Name <[email protected]>"]
5-
edition = "2018"
4+
edition = "2021"
65

76
[dependencies]
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
$ cargo run
2+
Compiling closure-example v0.1.0 (file:///projects/closure-example)
3+
error[E0308]: mismatched types
4+
(エラー: 型が合いません)
5+
--> src/main.rs:5:29
6+
|
7+
5 | let n = example_closure(5);
8+
| --------------- ^- help: try using a conversion method: `.to_string()`
9+
| | | (ヘルプ: 変換メソッド`.to_string()`を使用してみてください)
10+
| | |
11+
| | expected `String`, found integer
12+
| | (`String`を予期していましたが、整数が見つかりました)
13+
| arguments to this function are incorrect
14+
| (この関数への引数が正しくありません)
15+
|
16+
note: expected because the closure was earlier called with an argument of type `String`
17+
(注釈: クロージャは以前に型`String`を持つ引数とともに呼ばれているため、これが予期されています)
18+
--> src/main.rs:4:29
19+
|
20+
4 | let s = example_closure(String::from("hello"));
21+
| --------------- ^^^^^^^^^^^^^^^^^^^^^ expected because this argument is of type `String`
22+
| | (この引数が型`String`を持つことから予期されています)
23+
| |
24+
| in this closure call
25+
| (このクロージャ呼び出しで)
26+
note: closure parameter defined here
27+
--> src/main.rs:2:28
28+
|
29+
2 | let example_closure = |x| x;
30+
| ^
31+
32+
For more information about this error, try `rustc --explain E0308`.
33+
error: could not compile `closure-example` (bin "closure-example") due to 1 previous error

0 commit comments

Comments
 (0)