From 761e1e43531154dbb438fa10c0f7ca361c760f3d Mon Sep 17 00:00:00 2001 From: Konstantin Chaika Date: Wed, 15 Jan 2025 17:54:15 +0400 Subject: [PATCH] Added details about parse and expect methods --- .../Basic Data Types/Intro/task.md | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/Common Programming Concepts/Basic Data Types/Intro/task.md b/Common Programming Concepts/Basic Data Types/Intro/task.md index c1793784..e4890aaa 100644 --- a/Common Programming Concepts/Basic Data Types/Intro/task.md +++ b/Common Programming Concepts/Basic Data Types/Intro/task.md @@ -8,6 +8,26 @@ Keep in mind that Rust is a _statically typed language_, which means that it mus let guess: u32 = "42".parse().expect("Not a number!"); ``` +
+ + Although the example is focused on type annotation, it uses the `parse` and `expect` methods. + We won't pay much attention to them now, but for a general understanding, they are used for the following: + - `parse` converts a string to another type (number in this instance) and returns either a value or `Err`; + - `expect` allows you to set a custom error message for panic in case `parse` returns `Err`. + + For example, this code + ```rust + let guess: u32 = "a42".parse().expect("Not a number!"); + ``` + will cause the following error: + ```text + thread 'main' panicked at Common Programming Concepts/Basic Data Types/Intro/src/main.rs:2:36: + Not a number!: ParseIntError { kind: InvalidDigit } + ... +``` +
+ + If we don’t add the type annotation here, Rust will display the following error, which means the compiler needs more information from us to know which type we want to use: ```text