函數(shù)
函數(shù)的用處在于代碼封裝和復用
聲明函數(shù)
通過使用fn關鍵字我們可以聲明一個函數(shù)
fn test() {
println!("test")
}
調用函數(shù)
和其他語言一樣函數(shù)名稱加括號
fn main() {
test()
}
fn test() {
println!("test")
}
表達式
在Rust中我們可以為一個變量設定一個函數(shù)表達式以設定變量的值
let x = {
5+9
};
相當于寫成:
let x = add();
fn add(){
return 5+9
}
注釋
所有程序員都力求使其代碼易于理解,不過有時還需要提供額外的解釋,這就是注釋
單行注釋
//
多行注釋
/**/
文檔注釋(重要)
///
Rust可以檢測你的文檔注釋中的代碼是否有問題,這既可以保證代碼的正確性也能保證文檔的實時性
控制流
根據(jù)條件是否為真來決定是否執(zhí)行某些代碼
if-else判斷
fn main() {
let n = 5;
if n > 6 {
println!("1")
} else if n == 6 {
println!("2")
}else {
println!("3")
}
}
loop循環(huán)
loop 關鍵字告訴 Rust 一遍又一遍地執(zhí)行一段代碼直到你明確要求停止
loop{
//...
}
跳出loop
loop{
//...
break;
}
跳出并攜帶返回值
loop{
//...
break 返回值;
}
跳出指定循環(huán)
我們可能會遇到多個循環(huán)疊加的情況,當內部循環(huán)結束需要跳出外部循環(huán)時這很有效,而這也是Rust生命周期的妙用文章來源:http://www.zghlxwxcb.cn/news/detail-413803.html
'out:loop{
'mid:loop{
'inner:loop{
break 'out;
}
}
}
while循環(huán)
fn main() {
let n = 5;
while n-1>0{
//....
}
}
for循環(huán)
Rust中的for比較像python的因為他就是for-in文章來源地址http://www.zghlxwxcb.cn/news/detail-413803.html
let eles = [1,2,3]
for ele in eles{
//...
}
for i in (0..10){
//...
}
到了這里,關于研讀Rust圣經(jīng)解析——Rust learn-4(函數(shù),注釋,控制流)的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!