DEV Community

BC
BC

Posted on

Day1:Print - 100DayOfRust

1, Print

fn main() {
    println!("hello world");
    println!("{} and {}", "Alice", "Bob");
    println!("hello {name}", name="Bo");
    println!("{} of {:b} people know bin", 1, 2);
}
Enter fullscreen mode Exit fullscreen mode

Result:

hello world
Alice and Bob
hello Bo
1 of 10 people know bin
Enter fullscreen mode Exit fullscreen mode

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);
}
Enter fullscreen mode Exit fullscreen mode

Result:

Person is Person {
    name: "Peter",
    age: 27,
}
Enter fullscreen mode Exit fullscreen mode

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);
}
Enter fullscreen mode Exit fullscreen mode

Result:

Point is Point (3, 4)
Enter fullscreen mode Exit fullscreen mode

Top comments (0)