分享好友 编程语言首页 频道列表

【转】rust--如何打印struct实例对象?

rust文章/教程  2023-02-09 10:300

 

 

原文:https://www.jianshu.com/p/0ba974c3eaad

 

【转】rust--如何打印struct实例对象?

 

 

 

 

fn example1() {
     // 第一种方法是给Struct增加一个derive(Debug).
     #[derive(Debug)]
     struct MyStruct {x: i32, y: i32}
     let ms = MyStruct {x: 0, y: 10};
     println!("{:?}", ms)
}


fn example2() {
     // 第二种方法是自己去实现一个Display.
     // Refer: https://***.com/questions/30253422/how-to-print-structs-and-arrays
     struct MyStruct {a: i32, b: i32}

     impl std::fmt::Display for MyStruct {
         fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
             write!(f, "(value a: {}, value b: {})", self.a, self.b)
         }
     }

     let ms = MyStruct { a: 0, b: 15 };
     println!("Used Display: {}", ms);
}


fn main() {
     example1();                // output: MyStruct { x: 0, y: 10 }
     example2();       // output: Used Display: (value a: 0, value b: 15)
}

  

----------------------------

 

fn main() {
    println!("Hello, world!");
    let mut x = 5;
    x += 2;
    println!("{}", x);
    println!("{} days", 31);
    // Without a suffix, 31 becomes an i32. You can change what type 31 is
    // by providing a suffix. The number 31i64 for example has the type i64.

    // There are various optional patterns this works with. Positional
    // arguments can be used.
    println!("{0}, this is {1}. {1}, this is {0}", "Alice", "Bob");

    // As can named arguments.
    println!(
        "{subject} {verb} {object}",
        object = "the lazy dog",
        subject = "the quick brown fox",
        verb = "jumps over"
    );

    // Special formatting can be specified after a `:`.
    println!(
        "{} of {:b} people know binary, the other half doesn't",
        1, 2
    );

    // You can right-align text with a specified width. This will output
    // "     1". 5 white spaces and a "1".
    println!("{number:>width$}", number = 1, width = 6);

    // You can pad numbers with extra zeroes. This will output "000001".
    println!("{number:0>width$}", number = 1, width = 6);

    // Rust even checks to make sure the correct number of arguments are
    // used.
    println!("My name is {0}, {1} {0}", "Bond", "jjj");
    // FIXME ^ Add the missing argument: "James"

    // Create a structure named `Structure` which contains an `i32`.
    // #[allow(dead_code)]
    // #[derive(Debug)]
    struct MStructure(i32);

    impl std::fmt::Display for MStructure {
        fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
            write!(f, "(value a: {})", self.0)
        }
    }

    // // However, custom types such as this structure require more complicated
    // // handling. This will not work.
    // // println!("This struct `{}` won't print...", Structure(3));
    // // FIXME ^ Comment out this line.
    let ms = MStructure(3);
    println!("{}", ms);
    // #[derive(Debug)]
    // struct MyStruct {
    //     x: i32,
    //     y: i32,
    // }
    // let ms = MyStruct { x: 0, y: 10 };
    // println!("{:?}", ms)

    // #[derive(Debug)]
    // struct MyyStruct(i32);
    // let mm = MyyStruct(33);
    // println!("{:?}", mm)
}

  

查看更多关于【rust文章/教程】的文章

展开全文
相关推荐
反对 0
举报 0
评论 0
图文资讯
热门推荐
优选好物
更多热点专题
更多推荐文章
Rust到底值不值得学--Rust对比、特色和理念
前言其实我一直弄不明白一点,那就是计算机技术的发展,是让这个世界变得简单了,还是变得更复杂了。当然这只是一个玩笑,可别把这个问题当真。然而对于IT从业者来说,这可不是一个玩笑。几乎每一次的技术发展,都让这个生态变得更为复杂。“英年早秃”已经成

0评论2023-03-08818

全栈程序员的新玩具Rust(三)板条箱
上次用到了stdout,这次我们来写一个更复杂一点的游戏rust的标准库叫做std,默认就会引入。这次我们要用到一个随机数函数,而随机数比较尴尬的一点是这玩意不在标准库中,我们要额外依赖一个库。很多编程方案都有自己的模块化库系统,rust也不例外,不过rust

0评论2023-02-10729

【Rust】标准库-Result rust数据库
环境Rust 1.56.1VSCode 1.61.2概念参考:https://doc.rust-lang.org/stable/rust-by-example/std/result.html示例main.rsmod checked {#[derive(Debug)]pub enum MathError {DivisionByZero,NonPositiveLogarithm,NegativeSquareRoot,}pub type MathResult =

0评论2023-02-09978

【Rust】标准库-引用 rust 数据库框架
环境Rust 1.56.1VSCode 1.61.2概念参考:https://doc.rust-lang.org/stable/rust-by-example/std/rc.html示例rust 使用 Rc 来实现引用计数。main.rsuse std::rc::Rc;fn main() {let rc_examples = "Rc examples".to_string();{println!("--- rc_a is created

0评论2023-02-09638

rust 打印当前时间
let now = time::now();let f_now = time::strftime("%Y-%m-%dT%H:%M:%S", now).unwrap();println!("now: {:?}", f_now);

0评论2023-02-09689

【Rust】线程 rust编程语言
环境Rust 1.56.1VSCode 1.61.2概念参考:https://doc.rust-lang.org/stable/rust-by-example/std_misc/threads.html示例main.rsuse std::thread;const N_THREADS: u32 = 10;fn main() {let mut children = vec![];for i in 0..N_THREADS {children.push(threa

0评论2023-02-09956

rust安装 rust安装在固态进不去游戏
http://blog.csdn.net/teamlet/article/details/50838996

0评论2023-02-09614

更多推荐