我试图从一个结构的字段中导出一个值,该字段是一个枚举,以避免键入错误,它抛出了一个错误,我不能返回它,我真的不知道我能做什么
无法移出位于共享引用移动之后的self.package
,因为self.package
具有类型issues::PackageManager
,该类型未实现Copy
trait
pub enum PackageManager {
NPM,
PNPM,
YARN,
}
pub struct ProjectStruct {
name: String,
description: String,
version: u8,
package: PackageManager,
}
pub trait Project {
fn new(name: String, description: String) -> Self;
fn set_version(&mut self, version: u8);
fn get_version(&self) -> u8;
fn set_name(&mut self, name: String);
fn get_name(&self) -> String;
fn set_package_manager(&mut self, package_manager: PackageManager);
fn get_package_manager(&self) -> PackageManager;
}
impl Project for ProjectStruct {
fn new(name: String, description: String) -> Self {
ProjectStruct {
name,
description,
version: 1,
package: PackageManager::PNPM,
}
}
fn set_version(&mut self, version: u8) {
self.version = version
}
fn get_version(&self) -> u8 {
self.version
}
fn set_name(&mut self, name: String) {
self.name = name
}
fn get_name(&self) -> String {
self.name.clone()
}
fn set_package_manager(&mut self, package_manager: PackageManager) {
self.package = package_manager
}
fn get_package_manager(&self) -> PackageManager {
/* * no error
match self.package {
PackageManager::NPM => PackageManager::NPM,
PackageManager::PNPM => PackageManager::PNPM,
PackageManager::YARN => PackageManager::YARN,
}*/
// error
self.package
/* *cannot move out of `self.package` which is behind a shared reference
move occurs because `self.package` has type `issues::PackageManager`, which does not implement the `Copy` traitrustc */
}
}
返回不带开关的字段的值,因为它可以包含多个选项
1条答案
按热度按时间vh0rcniy1#
错误“doesn't implement the
Copy
trait”为您指出了正确的方向。您所需要做的就是为该类型实现Copy
,这可以通过一个简单的派生来完成。playground