1, Print
fn main() {
println!("hello world");
println!("{} and {}", "Alice", "Bob");
println!("hello {name}", name="Bo");
println!("{} of {:b} people know bin", 1, 2);
}
Result:
hello world
Alice and Bob
hello Bo
1 of 10 people know bin
2, Print self-defined structure
#[derive(Debug)]
struct Person<'a> {
name: &'a str,
age: u8
}
fn main() {
let name = "Peter";
let age = 27;
let peter = Person {name, age};
println!("Person is {:#?}", peter);
}
Result:
Person is Person {
name: "Peter",
age: 27,
}
3, Implement Display traits for print
use std::fmt;
struct Point {
x: i32,
y: i32,
}
impl fmt::Display for Point {
fn fmt(&self, f:&mut fmt::Formatter) -> fmt::Result {
write!(f, "Point ({}, {})", self.x, self.y)
}
}
fn main() {
let p = Point {x: 3, y: 4};
println!("Point is {}", p);
}
Result:
Point is Point (3, 4)
Top comments (0)