Rust enum和String相互转换

在这里插入图片描述

trait说明

  1. 为enum实现Display接口后,可以通过to_string获取到String类型的enum值
  2. 为String实现From<Platform>,可以在调用into函数将enum转为String
  3. 同理,为enum实现From<String>,也可以将String转为enum

使用例子

use core::fmt::{Display, Formatter, Result};  
  
#[derive(Debug)]  
enum Platform {  
    Linux,  
	MacOS,  
	Windows,  
	Unknown,  
}  
  
impl Display for Platform {  
    fn fmt(&self, f: &mut Formatter) -> Result {  
        match self {  
            Platform::Linux => write!(f, "Linux"),  
			Platform::MacOS => write!(f, "MacOS"),  
			Platform::Windows => write!(f, "Windows"),  
			Platform::Unknown => write!(f, "unknown"),  
		}  
    }  
}  
  
impl From<Platform> for String {  
    fn from(platform: Platform) -> Self {  
        match platform{  
            Platform::Linux => "Linux".into(),  
			Platform::MacOS => "MacOS".into(),  
			Platform::Windows => "Windows".into(),  
			Platform::Unknown => "unknown".into(),  
		}  
    }  
}  
  
impl From<String> for Platform{  
    fn from(platform: String) -> Self {  
        match platform {  
            platform if platform == "Linux" => Platform::Linux,  
			platform if platform == "MacOS" => Platform::MacOS,  
			platform if platform == "Windows" => Platform::Windows,  
		    platform if platform == "unknown" => Platform::Unknown,  
			_ => Platform::Unknown,  
		 }  
    }  
}  
  
fn main(){  
	let platform: String = Platform::MacOS.to_string();  
	println!("{}", platform);  
	let platform: String = Platform::Linux.into();  
	println!("{}", platform);  
	let platform: Platform = "Windows".to_string().into();  
	println!("{}", platform);  
}
  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值