[Rust] Instantiating Classic, Tuple, and Unit structs

https://doc.rust-lang.org/book/ch05-01-defining-structs.html

 

struct ColorClassicStruct {
    red: i32,
    green: i32,
    blue: i32
}

struct ColorTupleStruct(i32, i32, i32);

#[derive(Debug)]
struct UnitLikeStruct;

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn classic_c_structs() {
        // TODO: Instantiate a classic c struct!
        let red = 0;
        let green = 255;
        let blue = 0;
        let green = ColorClassicStruct {red, green, blue};

        assert_eq!(green.red, 0);
        assert_eq!(green.green, 255);
        assert_eq!(green.blue, 0);
    }

    #[test]
    fn tuple_structs() {
        let green = ColorTupleStruct(0, 255, 0);

        assert_eq!(green.0, 0);
        assert_eq!(green.1, 255);
        assert_eq!(green.2, 0);
    }

    #[test]
    fn unit_structs() {
        let unit_like_struct = UnitLikeStruct;
        let message = format!("{:?}s are fun!", unit_like_struct);

        assert_eq!(message, "UnitLikeStructs are fun!");
    }
}

 

posted @ 2024-02-23 19:11  Zhentiw  阅读(7)  评论(0编辑  收藏  举报