官术网_书友最值得收藏!

Playing with Options

To explain briefly how it works, when the Option type is Some, it simply means it contains a value whereas None doesn't. It has already been explained in Chapter 1, Basics of Rust, but here's a little recap just in case you need one. We can compare this mechanism with pointers in C-like languages; when the pointer is null, there is no data to access. The same goes for None.

Here's a short example:

    fn pide(nb: u32, pider: u32) -> Option<u32> {
      if pider == 0 {
        None
      } else {
          Some(nb / pider)
        }
    }  

So here, if the pider is 0, we can't pide or we'll get an error. Instead of setting an error or returning a complicated type, we just return an Option:

    let x = pide(10, 3);
    let y = pide(10, 0);

Here, x is equal to Some(3) and y is equal to None.

The biggest advantage of this type compared to null is that if we have Some, you're sure that the data is valid. And in addition, when it's None, you can't accidentally read its content, it's simply impossible in Rust (and if you try to unwrap it, your program will panic immediately, but at least, you'll know what failed and why—no magical segmentation fault).

You can take a look at its documentation at https://doc.rust-lang.org/std/option/enum.Option.html.

Let's explain what happens here:

  1. We create a texture or return None if the creation fails.
  2. We set the color and then fulfill the texture with it.
  3. We return the texture.

If we return None, it simply means an error occurred. Also, for now, this function only handles two colors, but it's pretty easy to add more if you want.

It might look a bit complicated at the moment, but it'll make our life easier afterward. Now, let's call this function by creating a blue square of size 32x32:

    let mut blue_square = create_texture_rect(&mut canvas,
        &texture_creator,
        TextureColor::Blue,
        TEXTURE_SIZE).expect("Failed to create a texture");

Easy, right?

Now we can just put pieces together. I'll let you try to handle the color switch. A small tip: take a look at the SystemTime struct. You can refer to its documentation at https://doc.rust-lang.org/stable/std/time/struct.SystemTime.html.

主站蜘蛛池模板: 紫金县| 双城市| 皮山县| 田阳县| 定安县| 饶河县| 长白| 上思县| 盐池县| 青岛市| 湖州市| 长沙县| 兴城市| 万全县| 县级市| 宁津县| 沭阳县| 靖西县| 富锦市| 蕲春县| 苏尼特左旗| 泰兴市| 湖北省| 镇平县| 湖南省| 澄迈县| 山西省| 唐河县| 海宁市| 聂荣县| 陈巴尔虎旗| 新民市| 平山县| 贵港市| 沙坪坝区| 安吉县| 敦化市| 黑水县| 英德市| 桐城市| 鄱阳县|