【08】Rust语法基础(下)

  • 董承泽
  • 更新于 2024-05-06 23:42
  • 阅读 795

Rust基础 下

配套视频教程:\ Bilibili:https://www.bilibili.com/video/BV1GM4m1Z7CA/?share_source=copy_web&vd_source=c147db41bce0140aa28781d353032bab\ Youtube:https://www.youtube.com/watch?v=lUOoseQXYPo\ 欢迎添加我的联系方式:Rico_Ruilabs

详解移步:https://tourofrust.com/00_zh-cn.html

结构体

struct SeaCreature {
    animal_type: String,
    name: String,
    arms: i32,
    legs: i32,
    weapon: String,
}

fn main() {

    let ferris = SeaCreature {
        animal_type: String::from("螃蟹"),
        name: String::from("Ferris"),
        arms: 2,
        legs: 4,
        weapon: String::from("大钳子"),
    };

    let sarah = SeaCreature {
        animal_type: String::from("章鱼"),
        name: String::from("Sarah"),
        arms: 8,
        legs: 0,
        weapon: String::from("无"),
    };

    println!(
        "{} 是只{}。它有 {} 只胳膊 {} 条腿,还有一个{}。",
        ferris.name, ferris.animal_type, ferris.arms, ferris.legs, ferris.weapon
    );
    println!(
        "{} 是只{}。它有 {} 只胳膊 {} 条腿。它没有杀伤性武器…",
        sarah.name, sarah.animal_type, sarah.arms, sarah.legs
    );
}

枚举

#![allow(dead_code)] 

enum Species {
    Crab,
    Octopus,
    Fish,
    Clam
}

struct SeaCreature {
    species: Species,
    name: String,
    arms: i32,
    legs: i32,
    weapon: String,
}

fn main() {
    let ferris = SeaCreature {
        species: Species::Crab,
        name: String::from("Ferris"),
        arms: 2,
        legs: 4,
        weapon: String::from("claw"),
    };

    match ferris.species {
        Species::Crab => println!("{} is a crab",ferris.name),
        Species::Octopus => println!("{} is a octopus",ferris.name),
        Species::Fish => println!("{} is a fish",ferris.name),
        Species::Clam => println!("{} is a clam",ferris.name),
    }
}
点赞 0
收藏 0
分享
本文参与登链社区写作激励计划 ,好文好收益,欢迎正在阅读的你也加入。

0 条评论

请先 登录 后评论
董承泽
董承泽
0x513D...fEC0
VX:ruichao_web3 bilibili :https://space.bilibili.com/434418210 youtube :https://www.youtube.com/channel/UCbVSj4aA2TAR9cUZuSoql5A