118 lines
2.4 KiB
Text
118 lines
2.4 KiB
Text
{
|
|
"cells": [
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"# Errors"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"1."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"metadata": {
|
|
"vscode": {
|
|
"languageId": "rust"
|
|
}
|
|
},
|
|
"outputs": [],
|
|
"source": [
|
|
"// FILL in the blanks and FIX the errors\n",
|
|
"use std::num::ParseIntError;\n",
|
|
"use std::num::IntErrorKind::InvalidDigit\n",
|
|
"\n",
|
|
"fn multiply(n1_str: &str, n2_str: &str) -> Result<i32, ParseIntError> {\n",
|
|
" let n1 = n1_str.parse::<i32>();\n",
|
|
" let n2 = n2_str.parse::<i32>();\n",
|
|
" \n",
|
|
" n1 * n2\n",
|
|
"}\n",
|
|
"\n",
|
|
"fn main() {\n",
|
|
" let result = multiply(\"10\", \"2\");\n",
|
|
" assert_eq!(result, Ok(20));\n",
|
|
"\n",
|
|
" let result = multiply(\"t\", \"2\");\n",
|
|
" assert_eq!(result.err().unwrap().kind(), &InvalidDigit);\n",
|
|
"\n",
|
|
" println!(\"Success!\");\n",
|
|
"}\n",
|
|
"\n",
|
|
"main();"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"2."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"metadata": {
|
|
"vscode": {
|
|
"languageId": "rust"
|
|
}
|
|
},
|
|
"outputs": [],
|
|
"source": [
|
|
"use std::fs;\n",
|
|
"use std::io;\n",
|
|
"use std::num;\n",
|
|
"\n",
|
|
"enum CliError {\n",
|
|
" IoError(io::Error),\n",
|
|
" ParseError(num::ParseIntError),\n",
|
|
"}\n",
|
|
"\n",
|
|
"impl From<io::Error> for CliError {\n",
|
|
" // TODO: implement the trait\n",
|
|
"}\n",
|
|
" \n",
|
|
"impl From<num::ParseIntError> for CliError {\n",
|
|
" // TODO: implement the trait\n",
|
|
"}\n",
|
|
"\n",
|
|
"fn open_and_parse_file(file_name: &str) -> Result<i32, CliError> {\n",
|
|
" // ? automatically converts io::Error to CliError\n",
|
|
" let contents = fs::read_to_string(&file_name)?;\n",
|
|
" // num::ParseIntError -> CliError\n",
|
|
" let num: i32 = contents.trim().parse()?;\n",
|
|
" Ok(num)\n",
|
|
"}\n",
|
|
"\n",
|
|
"fn main() {\n",
|
|
" println!(\"Success!\");\n",
|
|
"}\n",
|
|
"\n",
|
|
"main();"
|
|
]
|
|
}
|
|
],
|
|
"metadata": {
|
|
"kernelspec": {
|
|
"display_name": "Rust",
|
|
"language": "rust",
|
|
"name": "rust"
|
|
},
|
|
"language_info": {
|
|
"codemirror_mode": "rust",
|
|
"file_extension": ".rs",
|
|
"mimetype": "text/rust",
|
|
"name": "Rust",
|
|
"pygment_lexer": "rust",
|
|
"version": ""
|
|
}
|
|
},
|
|
"nbformat": 4,
|
|
"nbformat_minor": 2
|
|
}
|