Display Trait
Display trait สำหรับ user-facing output formatting
Implementing Display
Section titled “Implementing Display”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, "({}, {})", self.x, self.y) }}
struct Temperature { celsius: f64,}
impl fmt::Display for Temperature { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{:.1}°C", self.celsius) }}
fn main() { let point = Point { x: 10, y: 20 }; let temp = Temperature { celsius: 25.5 };
// print! and println! use Display println!("Point: {}", point); println!("Temperature: {}", temp);
// format! uses Display let s = format!("Point is {} and temperature is {}", point, temp); println!("{}", s);
// to_string() uses Display let point_str = point.to_string(); println!("As string: {}", point_str);}เข้าสู่ระบบเพื่อดูเนื้อหาเต็ม
ยืนยันตัวตนด้วยบัญชี Google เพื่อปลดล็อกบทความทั้งหมด
Login with Google