https://doc.rust-lang.org/rust-by-example/hello/print.html
Rust는 클래스가 아니라 struct를 사용한다.
struct의 원소를 console에서 보고 싶은 개발자를 위한 impl을 제공하는데 그것이 Display와 Debug다.
Display는 자바의 toString과 유사하게 개발자가 출력문을 커스텀할 수 있다. Debug는 struct를 디버깅하기 위해서 struct + 원소들을 출력하는 기능을 한다.(이것도 본인 커스텀할 수 있긴 하다.)
// #[derive(Debug)]이걸 통해서 개발자가 fmt출력문을 따로 만들지 않아도 debug 출력문의
// 포멧을 사용하면 struct의 이름과 원소들이 출력된다.
#[derive(Debug)]
struct Point2D {
x: f64,
y: f64,
}
// fmt::Display를 impl하고 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result{}
// 의 내용물을 채우면 struct를 출력할 수 있다. 이때 fmt의 write가 적용되어서 출력된다.
impl fmt::Display for Point2D {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
// Customize so only `x` and `y` are denoted.
write!(f, "x: {}, y: {}", self.x, self.y)
}
}
let point = Point2D { x: 3.3, y: 7.2 };
println!("Compare points:");
println!("Display: {}", point);
println!("Debug: {:?}", point);
std::fmt contains many traits which govern the display of text. The base form of two important ones are listed below:
fmt::Debug: Uses the {:?} marker. Format text for debugging purposes.
fmt::Display: Uses the {} marker. Format text in a more elegant, user friendly fashion.
디버깅하고 싶으면 Debug를 사용하고 특정 원소들만 출력하고 싶으면 Display를 사용
그 외에도 fmt 관련 함수들이 많음. 공식문서 잘 볼 것.