Types with generic type parameters

When a data type has generic type parameters, it's not, strictly speaking, actually a data type at all. It is a whole family of data types. Let's look at Option for a moment. Option is defined as follows:

pub enum Option<T> {
None,
Some(T),
}

This means that it has one generic type parameter with the name T. If we try to use Option without specifying a type for that generic type parameter, Rust will report an error:

let x: Option = None;

It produces this error:

What that's telling us, in essence, is that Option isn't a usable data type. However, Option<u32> is, as is Option<String>, Option<Result<f64, String>>, and so on. Moreover, Option<u32> and Option<String> are not the same type, and Rust won't pretend that they are. They're two different data types that have the same shape, as it were.

When we write Option<String>, we're telling Rust that it should make a data type by substituting String for the T in the definition of Option.

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

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