【rust】关于enum、mod、struct、match、方法、函数相关的demo

1.环境

cargo 1.52.0 (69767412a 2021-04-21)
rustc 1.52.0 (88f19c6da 2021-05-03)
ubuntu 1804

2.源码及分析

/// 功能:定义两个学生,包含学号和成绩,比较两个学生的学号大小和成绩大小并输出
/// data : 2021.5.18
/// NULL

/* 0.定义一个学生结构体,包含学号和成绩 */
struct Stu{
    id:u32,
    score:u32,
}
/* 0.1. 为上述结构体添加函数、方法 */
impl Stu{
    fn set_info(id:u32 , score:u32)->Stu{
        Stu{
            id,
            score,
        }
    }
    fn show_info(&self){
        println!("id={} ,   score={}",self.id,self.score);
    }
}
/* 0.2. 用于存储比较后的结果 */
pub enum RetSta{
    Sta(i32),
}

/* 0.3 定义一个crate::pack::module基本框架,全部为public
 * 主要为两个功能函数:
 * crate::student::cmp::cmp_id();
 * crate::student::cmp::cmp_score();
 * 用于说明super关键字的函数
 * crate::student::cmp_info::cmp_score()
 */
mod student{
    pub mod cmp{
    //mod cmp{ // error
	    /* 返回比较的状态, 对应1 0 -1 */
        pub fn cmp_id(&a:&u32 , &b:&u32)->i32{
            //println!("get a = {} , get b = {}",a ,b);
            if a == b {
                return 0
            }
            if a > b {1} else {-1}
        }
        /* 返回比较的状态,type为RetSta::Sta , */
        pub fn cmp_score(&a:&u32,&b:&u32)->crate::RetSta{
            //println!("get a = {} , get b = {}",a ,b);
            let mut sta = crate::RetSta::Sta(0);
            if a > b {
                sta = crate::RetSta::Sta(1);
            }else if a < b {
                sta = crate::RetSta::Sta(-1);
            }
            return sta;
        }
    }
    /* 为super关键字说明而定义的函数 */
    pub mod cmp_info{
        pub fn cmp_score(&a:&u32,&b:&u32)->crate::RetSta{
            //return super::cmp::cmp_score(&a,&b);
            super::cmp::cmp_score(&a,&b)
        }
    }
}

/* 1.main */
fn main() {
	/* 1.1 定义两个实例 ,通过"函数"定义 */
    let s1 = Stu::set_info(1,99);
    let s2 = Stu::set_info(2,98);
    /* 1.2 输出上述两个实例的信息,通过"方法"输出 */
    s1.show_info();
    s2.show_info();
	
	/* 1.3 调用mod中pub函数,比较两个实例id的大小,并判断返回值的大小、输出比较结果*/
    let ret = student::cmp::cmp_id(&s1.id , &s2.id);
    if ret > 0 {
        println!("s1.id > s2.id");
    }else if ret == 0{
        println!("s1.id = s2.id");
    }else{
        println!("s1.id < s2.id");
    }
	/* 1.4 调用mod中pub函数,比较两个实例id的大小,返回enum,通过match和enum判断返回值的大小、输出比较结果*/
    let ret = student::cmp_info::cmp_score(&s1.score , &s2.score);
    match ret {
        RetSta::Sta(1)  =>  println!("s1.score > s2.score"),
        RetSta::Sta(0)  =>  println!("s1.score = s2.score"),
        RetSta::Sta(-1) =>  println!("s1.score < s2.score"),
        _   => {},
    }
}

附件:源码下载

URL:https://download.csdn.net/download/yujianliam/18838309

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

过得精彩

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值