Error handling

Sometimes, we can anticipate the possibility that something could go wrong, or we're using a library function that knows it might not succeed. When that happens, we'll find ourselves using the special Result data type. The result is a generic type, which we'll talk about in a later chapter, but it's so integral to using functions that we're going to see how to use it here in a rote way.

A function that can fail will have a return type something like this: Result<i32, &'static str>. This looks kind of nuts at first glance, I admit. Let's break it down. The type starts off with Result followed by a <, then i32, then a ,, then &'static str, and finally a >. What that means is that the function will produce an i32 if it succeeds, and an &'static str if it fails. &'static str happens to be the type for a literal text expression, like oops, it broke, so what we're really saying here is that the function will return an integer or an error message.

It's common to have a data type specifically for representing errors, such as an Error structure, rather than just using a textual error message.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.138.122.11