也有英文版文章
Also this tutorial has been written in English
Check out my Medium
fn print_it(data: &str) {
println!("{:?}", data);
}
fn main() {
print_it("A string slice");
let owned_string = "owned string".to_owned();
let another_string = String::from("another");
print_it(&owned_string);
print_it(&another_string);
}
/*
"A string slice"
"owned string"
"another"
*/
struct LineItem {
name: String,
count: i32,
}
fn print_name(name: &str) {
println!("name: {:?}", name);
}
fn main() {
let receipt = vec![
LineItem {
name: "Apple".to_owned(),
count: 1,
},
LineItem {
name: String::from("Citrus"),
count: 3,
},
];
for item in receipt {
print_name(&item.name);
println!("count: {:?}", item.count);
}
}
/*
name: "Apple"
count: 1
name: "Citrus"
count: 3
*/
struct Person {
name: String,
fav_color: String,
age: i32,
}
fn print(data: &str) {
println!("{:?}", data);
}
fn main() {
let people = vec![
Person {
name: String::from("George"),
fav_color: String::from("green"),
age: 7,
},
Person {
name: String::from("Anna"),
fav_color: String::from("purple"),
age: 9,
},
Person {
name: String::from("Katie"),
fav_color: String::from("blue"),
age: 14,
},
];
for person in people {
if person.age <= 10 {
print(&person.name);
print(&person.fav_color);
}
}
}
/*
"George"
"green"
"Anna"
"purple"
*/