今年の言語はRust その１9


# 今年の言語はRust その１9


Rustを学びます


Rustの日本語ドキュメント 2nd Edition
https://doc.rust-jp.rs/book/second-edition/

オリジナル(英語)
https://doc.rust-lang.org/book/



#### 実行環境

```sh
$ cargo -V
cargo 1.33.0 (f099fe94b 2019-02-12)
$ rustup -V
rustup 1.17.0 (069c88ed6 2019-03-05)
$ rustc --version
rustc 1.33.0 (2aa4c46cf 2019-02-28)

$  cat /proc/version
Linux version 4.14.97-74.72.amzn1.x86_64 (mockbuild@gobi-build-64002) (gcc version 7.2.1 20170915 (Red Hat 7.2.1-2) (GCC)) #1 SMP Tue Feb 5 20:59:30 UTC 2019

$ uname -a
Linux ip-10-100-0-8 4.14.97-74.72.amzn1.x86_64 #1 SMP Tue Feb 5 20:59:30 UTC 2019 x86_64 x86_64 x86_64 GNU/Linux

$ cat /etc/\*release
NAME="Amazon Linux AMI"
VERSION="2018.03"
ID="amzn"
ID_LIKE="rhel fedora"
VERSION_ID="2018.03"
PRETTY_NAME="Amazon Linux AMI 2018.03"
ANSI_COLOR="0;33"
CPE_NAME="cpe:/o:amazon:linux:2018.03:ga"
HOME_URL="http://aws.amazon.com/amazon-linux-ami/"
Amazon Linux AMI release 2018.03

```


## エラー処理


### Resultで回復可能なエラー

```rust
enum Result<T, E> {
	Ok(T),
	Err(E),
}
```

```rust
use std::fs::FIle;

fn main(){
	let f = File::open("hello.txt");
}

===
error[E0308]: mismatched types
 --> src/main.rs:4:15
  |
4 |     let f: u32 = File::open("hello.txt");
  |                  ^^^^^^^^^^^^^^^^^^^^^^^ expected u32, found enum `std::result::Result`
  |
  = note: expected type `u32`
    
    found type `std::result::Result<std::fs::File, std::io::Error>`

```

簡単なエラーハンドリング

```rust
use std::fs::File;

fn main(){
	let f: std::result::Result<std::fs::File, std::io::Error> = File::open("hello.txt");
	
	let f = match f {
	    Ok(file) => file,
	    Err(error) => {
	        // Error!! file open
	        panic!("There was a problem opening the file: {:?}", error  );
	    }
	}
}

```

様々なエラーのハンドリング

```Rust
use std::fs::File;
use std::io::ErrorKind;

fn main(){

	let f: std::result::Result<std::fs::File, std::io::Error> = File::open("hello.txt");
	
	let f = match f {
	    Ok(file) => file,
	    Err(ref error) if error.kind() == ErrorKind::NotFound =>{
	        match File::create("hello2.txt"){
	            Ok(fc) => fc,
	            Err(e) => {
	                panic!("Error {:?}", e);
	            },
	        }
	    },
	    
	    Err(error) => {
	        // Error!! file open
	        panic!("There was a problem opening the file: {:?}", error);
	    },
	};
	
}


```

長い！

### エラー処理のショートカット！
が準備されております


```Rust

use std::fs::File;
use std::io::ErrorKind;

fn main(){

	let f = File::open("hello.txt").unwrap();
	
	let f = match f {
	    Ok(file) => file,
	    Err(error) => {
	        // Error!! file open
	        panic!("There was a problem opening the file: {:?}", error  );
	    }
	}
}


```

 __unwrap()__はResultのヘルパーメソッドである。
これは、OkならOkの中身を返し、エラーならpanicを呼んでくれる！


```rust
use std::fs::File;
use std::io::ErrorKind;

fn main(){

	let f = File::open("hello.txt").unwrap();
	
}

```


### エラーを譲渡する


```rust

use std::io;
use std::io::Read;
use std::fs::File;

fn read_username_from_file() -> Result<String, io::Error>{

	let f = File::open("hello.txt");

	let mut f = match f {
		Ok(file) => file,
		Err(e) => return Err(e),
	};
	
	let mut s = String::new();
	
	match f.read_to_string(&mut s) {
	    Ok(_) => Ok(s),
	    Err(e) => Err(e),
	}

}

fn main(){

	let r = read_username_from_file();
	
}


```

上を__ショートカット__で書くには__？__ 使うと良い




```rust
__asdf__
use std::io;
use std::io::Read;
use std::fs::File;

fn read_username_from_file() -> Result<String, io::Error>{

	let mut f = File::open("hello.txt")?; // ?<= まだパニックになってない
    let mut s = String::new();
    f.read_to_string(&mut s)?;				// ?
    Ok(s)
    
}

fn main(){

	let r = read_username_from_file();
	
}

````
さらに__ショートカット__


```rust
use std::io;
use std::io::Read;
use std::fs::File;

fn read_username_from_file() -> Result<String, io::Error>{

    let mut s = String::new();
    
    File::open("hello.txt")?.read_to_string(&mut s)?;
    
    Ok(s)
    
}

fn main(){
    
    
}

```



次回！


イエス！