- Rust Programming By Example
- Guillaume Gomez Antoni Boucher
- 367字
- 2021-07-02 19:13:05
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:
- We create a texture or return None if the creation fails.
- We set the color and then fulfill the texture with it.
- 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.
- 區(qū)塊鏈在電子檔案管理中的應(yīng)用
- 智慧場館與智慧學(xué)習(xí)
- 肖鷹文集初編·批評卷
- 圖書館學(xué)是什么
- 中國人民大學(xué)復(fù)印報刊資料轉(zhuǎn)載指數(shù)排名研究報告2016
- 文獻(xiàn)保護(hù)中英雙解詞語手冊
- 中國古代圖書館學(xué)研究
- 高校圖書館門戶網(wǎng)站建設(shè)(谷臻小簡·AI導(dǎo)讀版)
- 非物質(zhì)文化遺產(chǎn)數(shù)字化研究
- 檔案利用與服務(wù)
- 高校博物館發(fā)展研究:以上海地區(qū)為中心
- 四川文理學(xué)院校史(1976—2016)
- 圖書情報與圖書館服務(wù)探究
- 高校圖書館創(chuàng)新服務(wù)(谷臻小簡·AI導(dǎo)讀版)
- Web 2.0環(huán)境中參與式的信息檔案化管理:走向全景檔案世界