如何创建Struct方法并在Rust中使用它们

myzjeezk  于 2023-02-04  发布在  其他
关注(0)|答案(1)|浏览(152)

我对Rust编程语言比较陌生,我正在学习Struct和Enums。我创建了一个程序来存储一周中的哪一天,看看它是否是周末。代码如下:

#[derive(Debug)]
enum DaysOfTheWeekNames {
    Friday,
    Saturday,
    Sunday,
}

#[derive(Debug)]
struct Weekday {
    day: DaysOfTheWeekNames,
    weekend: bool,
}

impl Weekday {
    fn isWeekend(day: DaysOfTheWeekNames) -> bool {
        match day {
            DaysOfTheWeekNames::Saturday => false,
            DaysOfTheWeekNames::Sunday => false,
            other => true,
        }
    }
    
    fn new_day(day: DaysOfTheWeekNames) -> Self {
        Self { day, weekend: Weekday::isWeekend(day) }
    }
}

fn main() {
    let today = Weekday::new_day(DaysOfTheWeekNames::Saturday);
    println!("Today: {:#?}", today);
}

我的目标是创建一个名为Weekday的结构体,并使用名为new_day的方法初始化它(),我只传入工作日的名称,这个函数应该调用isWeekend()方法来确定是否是周末。但是上面的代码如预期的那样抛出了一个错误,因为变量name的所有权被转移到isWeekend函数,并且没有被转移回来。那么,编写这样一个用例的理想方式是什么?我们应该如何解决这个问题?
我看到的错误如下:

error[E0382]: use of moved value: `day`
   --> src/main.rs:115:50
    |
114 |     fn new(day: DaysOfTheWeek) -> Self {
    |            --- move occurs because `day` has type `DaysOfTheWeek`, which does not implement the `Copy` trait
115 |         Self { day, weekend: Weekday::is_weekend(day) }
    |                --- value moved here              ^^^ value used here after move
qybjjes1

qybjjes11#

已解决此问题。解释:由于isWeekend是一个结构体方法,我们不应该传递示例的结构体字段,我们已经在上面做了(例如day)。为了解决这个问题,我们必须复制或克隆day参数,然后将其传递给isWeekend()函数。
代码:

#[derive(Debug)]
#[derive(Clone, Copy)]
enum DaysOfTheWeekNames {
    Friday,
    Saturday,
    Sunday,
}

#[derive(Debug)]
struct Weekday {
    day: DaysOfTheWeekNames,
    weekend: bool,
}

impl Weekday {
    fn is_weekend(day: DaysOfTheWeekNames) -> bool {
        match day {
            DaysOfTheWeekNames::Saturday => true,
            DaysOfTheWeekNames::Sunday => true,
            _ => false,
        }
    }
    
    fn new_day(day: DaysOfTheWeekNames) -> Self {
        Self { day, weekend: Weekday::is_weekend(day.clone()) }
    }
}

fn main() {
    let today = Weekday::new_day(DaysOfTheWeekNames::Saturday);
    println!("Today: {:#?}", today);
}

相关问题