编者注:在Rust 1.0发布之前询问了这个问题
..并引入了"范围"操作符.问题的代码不再代表当前的样式,但下面的一些答案使用的代码可以在Rust 1.0及以后版本中使用.
我在Rust by Example网站上玩,想要反过来打印出fizzbuzz.这是我尝试过的:
fn main() {
// `n` will take the values: 1, 2, ..., 100 in each iteration
for n in std::iter::range_step(100u, 0, -1) {
if n % 15 == 0 {
println!("fizzbuzz");
} else if n % 3 == 0 {
println!("fizz");
} else if n % 5 == 0 {
println!("buzz");
} else {
println!("{}", n);
}
}
}
Run Code Online (Sandbox Code Playgroud)
没有编译错误,但它没有打印出任何东西.如何从100迭代到1?
我想创建一个带有'a'..'z'值(包括)的向量.
这不编译:
let vec: Vec<char> = ('a'..'z'+1).collect();
Run Code Online (Sandbox Code Playgroud)
什么是惯用的方式'a'..'z'?
我正在学习 Rust,最近进行了一次练习,我必须迭代可能朝任一方向发展的数字。我尝试了以下方法,得到了意想不到的结果。
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
struct Point {
x: i32,
y: i32
}
fn test() {
let p1 = Point { x: 1, y: 8 };
let p2 = Point { x: 3, y: 6 };
let all_x = p1.x..=p2.x;
println!("all_x: {:?}", all_x.clone().collect::<Vec<i32>>());
let all_y = p1.y..=p2.y;
println!("all_y: {:?}", all_y.clone().collect::<Vec<i32>>());
let points: Vec<Point> = all_x.zip(all_y).map(|(x, y)| Point { x, y }).collect();
println!("points: {:?}", points);
}
Run Code Online (Sandbox Code Playgroud)
输出是
all_x: [1, 2, 3]
all_y: []
points: []
Run Code Online (Sandbox Code Playgroud)
经过一番谷歌搜索后,我找到了一个解释和一些 …
我本周开始使用Rust编程,我在理解Strings如何工作方面遇到了很多问题.
现在,我正在尝试制作一个简单的程序,打印附加订单的玩家列表(仅用于学习目的).
let res : String = pl.name.chars().enumerate().fold(String::new(),|res,(i,ch)| -> String {
res+=format!("{} {}\n",i.to_string(),ch.to_string());
});
println!("{}", res);
Run Code Online (Sandbox Code Playgroud)
这是我的想法,我知道我可以使用for循环,但目标是了解不同的Iterator函数.
所以,我的问题是字符串连接不起作用.
Compiling prueba2 v0.1.0 (file:///home/pancho111203/projects/prueba2)
src/main.rs:27:13: 27:16 error: binary assignment operation `+=` cannot be applied to types `collections::string::String` and `collections::string::String` [E0368]
src/main.rs:27 res+=format!("{} {}\n",i.to_string(),ch.to_string());
^~~
error: aborting due to previous error
Could not compile `prueba2`.
Run Code Online (Sandbox Code Playgroud)
我尝试使用&str但是不可能从i和它创建它们ch.