Noneとエラー処理

fn main() {
	let mut data = vec![];
	for n in 0..5 {
		data.push(Some(n));
	}
	print_all(data);
}

fn print_all(data:Vec<Option<i32>>) {
	for item in data {
		println!("{:?}", item);
	}
}

Noneを含む処理

use rand::Rng;

fn random()-> Option<i32> {
	let n = rand::thread_rng().gen_range(0..10);
	match n {
		0 => None,
		_ => Some(n)
	}
}

fn main() {
	let mut data = vec![];
	for n in 0..10 {
		data.push(random(n));
	}
	print_all(data);
}

fn print_all(data:Vec<Option<i32>>) {
	for item in data {
		print(item);
	}
}

fn print(item:Option<i32>){
	match item {
		None => println!("no-data..."),
		Some(n) => println!("No, {}.", n)
	}
}

### Panicによる強制終了

fn print(item:Option<i32>){
	match item {
		None => panic!("NODATA!"),
		Some(n) => println!("No, {}.", n)
	}
}

### Resultによるエラーリカバリ

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

Errを使ってエラー処理を行う

fn print(item:Option<i32>)->Result<String, String>{
	match item {
		None => {
			Err(String::from("ERROR IS OCCURED."))
		},
		Some(n) => {
			println!("No, {}.", n);
			Ok(String::from("OK"))
		}
	}
}

### print_allでResultによるエラー処理を実装

fn print_all(data:Vec<Option<i32>>) {
	for item in data {
		let res = print(item);
		match res {
			Ok(s) => println!("--- {} ---", s),
			Err(s) => println!("*** {} ***", s)
		}
	}
}

### より細かなエラー処理
enum ErrKin {
Caution,
Danger
}

fn print_all(data:Vec<Option<i32>>) {
	for item in data {
		let res = print(item);
		match res {
			Ok(s) => println!("--- {} ---", s),
			Err(s) => match k {
				ErrKind::Caution => {
					println!("*** CAUTION!! ***");
				},
				ErrKind::Danger => {
					println!("DANGER!!");
					panic!("DANGER ERROR.");
				}
			}
		}
	}
}

fn print(item:Option<i32>)->Result<String, ErrKind>{
	match item {
		None => {
			Err(ErrKind::Danger)
		},
		Some(n) => {
			println!("No, {}.", n);
			if n == 1 {
				Err(ErrKind::Caution)
			} else {
				Ok(String::from("OK"))
			}
		}
	}
}