瀛︿範绗旇锛屼粎姝よ€屽凡
涓€銆佸嚱鏁?/h2>
Rust鍑芥暟鍛藉悕浣跨敤鍏抽敭瀛?code>fn锛岀被浼糺s鐨刦unction锛屽彉閲忓悕浣跨敤灏忓啓+涓嬪垝绾垮舰寮忋€俁ust鍑芥暟鏈夊涓嬬壒鐐?/p>
-
鍑芥暟澹版槑绫讳技js涓殑鍑芥暟澹版槑鎻愬崌锛屽彲浠ュ湪璋冪敤鍚庡0鏄?/p>
fn main1(){ say_hello(); } fn say_hello(){ println!("hello") }
-
褰撳嚱鏁版湁鍙傛暟鏃讹紝蹇呴』澹版槑鍙傛暟绫诲瀷
fn get_name(user: u32) { println!(user) }
-
褰撳嚱鏁版湁杩斿洖鍊兼椂锛屽繀椤诲0鏄庤繑鍥炵被鍨嬶紝浣跨敤
->
澹版槑杩斿洖绫诲瀷锛屽叾涓嚱鏁拌繑鍥炲€间互鍑芥暟鏈€鍚庝竴琛岃〃杈惧紡涓哄噯锛屼笉闇€瑕乺eturn鍏抽敭瀛楋紝鍙互鍦ㄦ潯浠跺垽鏂腑浣跨敤return鎻愬墠缁撴潫fn get_name() -> u32 { 6 }
鍑芥暟浣撶殑璇彞鍜岃〃杈惧紡锛?/h4>
- 鍑芥暟浣撴湁涓€绯诲垪鐨勮鍙ョ粍鎴愶紝璇彞鏄敱琛ㄨ揪寮忕粍鎴愶紝鍑芥暟鏈€绠€鍗曠殑鍙互浣跨敤涓€涓〃杈惧紡缁撴潫鍑芥暟浣撱€?
fn get_name() {
let x = 20+1;
}
- Rust鏄竴涓熀浜庤〃杈惧紡鐨勮瑷€
- 琛ㄨ揪寮忎細璁$畻浜х敓涓€涓€?/li>
- 鍑芥暟鐨勫畾涔変篃鏄鍙?/li>
- 璇彞娌℃湁杩斿洖鍊硷紝鎵€浠ヤ笉鑳戒娇鐢╨et灏嗕竴涓鍙ヨ祴缁欏彉閲?/li>
fn get_name() {
let x = 20+1;
}
鎵€浠ラ拡瀵逛笂杩颁唬鐮?/p>
- let x = 20; 鏄竴涓鍙?/li>
- 鏁翠釜鍑芥暟涔熸槸涓€涓鍙?/li>
- 20+1鏄竴涓〃杈惧紡锛屾墍浠ュ彲浠ョ敤let 鍘绘帴鏀讹紙 鍗曚釜20瀛楅潰閲忎篃鏄〃杈惧紡锛?/li>
閿欒鐨勪緥瀛愶細
fn get_name() {
let y = (let x = 20) 璇彞娌℃湁杩斿洖鍊硷紝涓嶈兘鐢╨et鎺ユ敹
}
鎵€浠ュ嚱鏁扮殑杩斿洖鍊间緷璧栫殑鏄渶鍚庝竴琛岀殑琛ㄨ揪寮忥紝鑰屼笉鏄鍙?/strong>
fn get_name() -> u32 {
6 6鏄竴涓〃杈惧紡锛屾渶缁堟渶涓哄嚱鏁扮殑杩斿洖鍊?
}
鍊煎緱娉ㄦ剰鐨勬槸锛屾槸鍚︽槸璇彞杩樻槸琛ㄨ揪寮忕湅浣犲悗闈㈡槸涓嶆槸甯﹀垎鍙蜂簡銆傘€傘€傘€?/strong>
fn get_name() -> u32 {
6; 甯︿笂鍒嗗彿涔嬪悗锛屽氨鏄竴涓鍙ヤ簡銆傘€傘€傚叾杩斿洖鍊煎氨涓嶆槸6浜?鑰屾槸涓€涓┖鐨則uple瀵硅薄锛岀紪璇戜篃浼氭姤閿欙紝鍥犱负澹版槑鐨勮繑鍥炲€肩被鍨嬫槸u32锛岀幇鍦ㄨ繑鍥炵殑鏄痶uole瀵硅薄
}
鎯婂徆馃悅馃嵑銆傘€傘€?/p>
浜屻€佹帶鍒舵祦
if琛ㄨ揪寮?/h3>
Rust涓殑if琛ㄨ揪寮忎腑鐨勬潯浠朵笉闇€瑕佸啓灏忔嫭鍙?鍖哄埆浜巎s)锛屼絾鏄富浣撹繕鏄緱閫氬ぇ鎷彿鍖呰9銆?/p>
fn say_hello() {
let x = 3;
if x > 3 {
println!("big")
}
}
if鍚庨潰璺熺殑鏉′欢蹇呴』杩斿洖涓€涓猙ool鍊肩被鍨嬶紝闈瀊ool鍊煎垯鎶ラ敊锛堝尯鍒簬js鐨勯殣绀鸿浆鎹級
fn say_hello() {
let x = "bob";
if x { 缂栬瘧鎶ラ敊锛?expected `bool`, found `&str`
println!("big")
}
}
else if澶勭悊澶氫釜鏉′欢
fn say_hello() {
let x = 3;
if x > 3 {
println!("big")
} else if x<2 {
println!("small")
} else {
println!("done")
}
}
濡傛灉瓒呰繃浣跨敤涓€涓猠lseif锛屾帹鑽愪娇鐢?code>match璇硶锛岀被浼间簬switch璇彞
鍙互鍦╨et璇彞涓娇鐢╥f
鍥犱负if鏄竴涓〃杈惧紡锛屽彲浠ュ皢鍏舵斁鍦╨et璇彞鍚庨潰
fn main() {
let condition = true;
let result = if condition { 4 } else { 5 };
println!("result鐨勫€间负{}", result) // result鍊间负4
}
杩欓噷鏈変竴涓墠鎻愭槸if璇彞閲屾渶缁堣繑鍥炵殑绫诲瀷瑕佷繚鎸佷竴鑷达紝涓嶇劧浼氭姤閿欍€?/p>
fn main() {
let condition = true;
let result = if condition { 4 } else { 's' };
println!("result鐨勫€间负{}", result) 缂栬瘧浼氭姤閿?
}
涓夈€佸惊鐜?/h2>
Rust寰幆鏈?绉嶏細loop銆亀hile銆乫or
loop姝诲惊鐜?/h3>
loop鏄竴涓寰幆
fn main() {
loop {
println!("hello") 姝诲惊鐜緭鍑篽ello
}
}
闄ら潪纰板埌break璇彞锛屼笅闈㈢殑浠g爜杈撳嚭 10娆′箣鍚庣粨鏉?/p>
fn main() {
let mut x = 0;
loop {
println!("hello");
x += 1;
if x == 10 {
break;
}
}
}
loop璇彞涔熷彲浠ヨlet鎺ユ敹锛屼笅闈㈢殑浠g爜鏈€缁堜細杈撳嚭10
fn main() {
let mut x = 0;
let y = loop {
x += 1;
if x == 10 {
break x;
}
};
println!("{}",y);
}
while鏉′欢寰幆
fn main() {
let mut x = 0;
while x < 3 {
x += 1;
println!("{}", x);
}
println!("寰幆缁撴潫浜?);
}
涓婅堪浠g爜鎵ц杈撳嚭
1
2
3
寰幆缁撴潫浜?
for寰幆閬嶅巻闆嗗悎
fn main() {
let array = [1, 2, 3, 4, 5];
for item in array.iter() {
println!("{}", item);
}
}
Rust涓璮or寰幆鏇村畨鍏ㄣ€佺畝娲侊紝鍦≧ust涓敤鐨勬渶澶?/p>