fn sum(slice: &[i32]) -> i32 { let mut total = 0; for &item in slice.iter() { total +=…
- User
fn sum(slice: &[i32]) -> i32 { let mut total = 0; for &item in slice.iter() { total += item; } total }
fn main() { let numbers = [1, 2, 3, 4, 5]; let result = sum(&numbers); println!("The sum is: {}", result); }
- Assistant
Your Rust code looks correct and will compile and run successfully. It defines a function
sumthat takes a slice ofi32integers and returns their sum. Themainfunction demonstrates usage by summing the array[1, 2, 3, 4, 5].When you run this program, it will output:
The sum is: 15
If you'd like, here are a couple of suggestions to make it more idiomatic:
- Using iterators and the
sum()method directly, you can simplify thesumfunction:
fn sum(slice: &[i32]) -> i32 { slice.iter().sum() }- Or you can even call
.iter().sum()directly inmainwithout a separate function, depending on your use case.
Let me know if you'd like help with that or anything else!
- Using iterators and the
- User
請用繁體
- Assistant
當然可以!以下是你原本程式碼的說明與簡單優化,使用繁體中文:
你的程式碼功能正確,會印出陣列中數字的總和:
fn sum(slice: &[i32]) -> i32 { let mut total = 0; for &item in slice.iter() { total += item; } total } fn main() { let numbers = [1, 2, 3, 4, 5]; let result = sum(&numbers); println!("The sum is: {}", result); }執行結果會是:
The sum is: 15
小建議
你可以用 Rust 提供的
sum()方法,讓程式碼更簡潔:fn sum(slice: &[i32]) -> i32 { slice.iter().sum() }這樣就不需要自己寫迴圈來累加。
如果你有其他問題,歡迎隨時跟我說!
- User
fn sum(slice: &[i32]) -> i32 { let mut total = 0; for &item in slice.iter() { total += item; } total }
fn main() { let numbers = [1, 2, 3, 4, 5]; let result = sum(&numbers); println!("The sum is: {}", result); }
- Assistant
你的程式碼功能正常,執行後會印出陣列數字的總和:
The sum is: 15如果想要用更簡潔的寫法,可以改成用
iter()搭配內建的sum()方法,例如:fn sum(slice: &[i32]) -> i32 { slice.iter().sum() } fn main() { let numbers = [1, 2, 3, 4, 5]; let result = sum(&numbers); println!("The sum is: {}", result); }這樣程式碼更簡短易懂。如果有其他問題,歡迎繼續問!
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.