字符、布爾、單元 類型
字符類型(char)
對(duì)于字符類型我們有更大的自由性,概括一下:
- 更大的編碼范圍,讓rust 可以展示更多的內(nèi)容。
- 統(tǒng)一的字節(jié)空間,字符也是四個(gè)字節(jié)的內(nèi)存大小。
- 嚴(yán)格區(qū)分的
""
和''
前者用于字符串、后者是字符。
fn test_math_4() {
let c = 'z';
let z = '?';
let g = '國(guó)';
let heart_eyed_cat = '??';
let x = '中';
println!("字符'中'占用了{(lán)}字節(jié)的內(nèi)存大小", std::mem::size_of_val(&x));
println!("{} \n{} \n{} \n{}\n", c, z, g, heart_eyed_cat);
}
fn main() {
test_math_4();
}
warning: `file23_06_28` (bin "file23_06_28") generated 4 warnings (run `cargo fix --bin "file23_06_28"` to apply 1 suggestion)
Finished dev [unoptimized + debuginfo] target(s) in 0.71s
Running `target\debug\file23_06_28.exe`
字符'中'占用了4字節(jié)的內(nèi)存大小
z
?
國(guó)
??
PS C:\Users\97852\Desktop\ZryCode\CODE\Rust\file23_06_28
布爾類型(bool)
說明一點(diǎn),bool
類型的應(yīng)用場(chǎng)景 主要就是用在流程控制中,
fn test_math_5() {
let t = false;
let f: bool = true; // 使用類型標(biāo)注,顯式指定f的類型
if f {
println!("這是段毫無意義的代碼");
}
}
fn main() {
test_math_5();
}
warning: `file23_06_28` (bin "file23_06_28") generated 6 warnings (run `cargo fix --bin "file23_06_28"` to apply 2 suggestions)
Finished dev [unoptimized + debuginfo] target(s) in 0.56s
Running `target\debug\file23_06_28.exe`
這是段毫無意義的代碼
單元類型(())
美妙的新鮮內(nèi)容。單元類型。
所謂單元類型,其實(shí)是一種語義補(bǔ)全,為了在rust 的強(qiáng)類型思想下,完成閉環(huán)。用來在一個(gè)沒有返回的函數(shù)中用來隱式說明返回了什么,
用法也很簡(jiǎn)單,你看到的 main()
、println!()
,以及后面的發(fā)散函數(shù)(發(fā)散函數(shù)( diverge function )
,顧名思義,無法收斂的函數(shù))也都是這個(gè)返回類型。文章來源:http://www.zghlxwxcb.cn/news/detail-521069.html
再比如,你可以用 ()
作為 map
的值,表示我們不關(guān)注具體的值,只關(guān)注 key
。 這種用法和 Go 語言的 struct{} 類似,可以作為一個(gè)值用來占位,但是完全不占用任何內(nèi)存。文章來源地址http://www.zghlxwxcb.cn/news/detail-521069.html
到了這里,關(guān)于Rust 基礎(chǔ)入門 —— 字符、布爾、單元 類型的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!