for x in range(0i, 10i) {
println!("{:d}", x);
}
while循环
let mut x = 5u;
let mut done = false;
while !done {
x += x - 3;
println!("{}", x);
if x % 5 == 0 { done = true; }
}
let mut x = 5u;
loop {
x += x - 3;
println!("{}", x);
if x % 5 == 0 { break; }
}
let mut s = "Hello".to_string();
println!("{}", s);
s.push_str(", world.");
println!("{}", s);
String转&str
fn takes_slice(slice: &str) {
println!("Got: {}", slice);
}
fn main() {
let s = "Hello".to_string();
takes_slice(s.as_slice());
}
比如字符串是否相同,推荐用:
fn compare(string: String) {
if string.as_slice() == "Hello" {
println!("yes");
}
}
而不要用
fn compare(string: String) {
if string == "Hello".to_string() {
println!("yes");
}
}
因为as_slice便宜,而 to_string()需要分配内存
12向量和数组
vec
let nums = vec![1i, 2i, 3i];vec![]和println!()后面的括号即可以使用()也可以使用[]
nums.push(4i); // works
let nums = [1i, 2i, 3i];
let nums = [1i, ..20]; // Shorthand for an array of 20 elements all initialized to 1
向量长度可变,数组是固定大小,不能使用push
let vec = vec![1i, 2i, 3i];
let slice = vec.as_slice();
vec, array和&str都实现了.iter方法
let vec = vec![1i, 2i, 3i];
for i in vec.iter() {
println!("{}", i);
}
end!