use rand::Rng; use std::cmp::Ordering; use std::io; fn main() { let guess = rand::thread_rng().gen_range(1, 101);//生成隨機數1~100,含左不含右 loop { let mut input = String::new();//據說沒有gc的語言字符串是個大坑 println!("請輸入你猜的數字。"); io::stdin().read_line(&mut input).expect("讀取錯誤");//讀取輸入 let input: u32 = match input.trim().parse() {//轉換爲數字 Ok(num) => num, Err(_) => { println!("請輸入數字!"); continue; }, }; println!("輸入數字:{}", input); match input.cmp(&guess) {//模式匹配,目前還沒看出和switch比有什麼優勢 Ordering::Equal => { println!("猜對了!"); break; } Ordering::Greater => println!("高了"), Ordering::Less => println!("低了"), } } }
對比C#,編程
1.use至關於using,引用各類庫。c#
2.let有點像var,均可以推斷類型,可是let能夠聲明類型,var只能推斷。dom
3.符號::和.目前尚未介紹用法,看的有點亂。編程語言
4.符號&是引用,等後面介紹吧。ide
5.模式匹配,C#好像新版本也有了,不過目前沒用到,如今感受有點怪怪的。oop
6.符號println!是個宏,記下來等後面解釋吧。學習
這段代碼大概至關於c#裏這樣的:spa
1 using System; 2 3 namespace ConsoleApp1 4 { 5 class Program 6 { 7 static void Main(string[] args) 8 { 9 Console.WriteLine("請輸入你猜的數字。"); 10 int guess = new Random().Next(1, 101); 11 while (true) 12 { 13 string input = Console.ReadLine(); 14 if (int.TryParse(input, out int num)) 15 { 16 if (num > guess) 17 { 18 Console.WriteLine("高了"); 19 } 20 else if (num < guess) 21 { 22 Console.WriteLine("低了"); 23 } 24 else 25 { 26 Console.WriteLine("猜對了!"); 27 break; 28 } 29 } 30 else 31 { 32 Console.WriteLine("請輸入數字!"); 33 continue; 34 } 35 } 36 37 } 38 } 39 }
這是學習《Rust編程語言》第二章的內容記錄code