如何读取与Rust中的自定义类型相关联的枚举的值? [英] How to read a value of an enum which associates with a custom type in Rust?
问题描述
我在Rust中有一个实现,如下所示.在主要功能中,我正在读取 SalaryRange
枚举中的一个值,它将显示 High("So High")
.
I have an implementation in Rust as follows. In the main function, I am reading a value in SalaryRange
enum and this will display High("So High")
.
// This can be a complex type, just using string for the question
type SRange = String;
type SalEnu = SalaryRange<SRange>;
struct User<SRange> {
username: String,
email: String,
sign_in_count: u64,
active: bool,
income: Income<SRange>,
}
struct Income<SRange> {
salary_range: SalaryRange<SRange>
}
#[derive(Debug)]
enum SalaryRange<SRange> {
Low(SRange),
Mid(SRange),
High(SRange),
}
fn main() {
let user1 = User {
email: String::from("test@email.com"),
username: String::from("test_name"),
active: true,
sign_in_count: 1,
income: Income {
salary_range: (
SalaryRange::High("So High")
)
},
};
let mut srange: SalaryRange<&str> = user1.income.salary_range;
println!("{:?}", srange);
}
此
Link for this example can be found here.
只想知道是否有可能以 println!("{:?}",srange :: High);
的形式读取和打印该枚举中的值字符串值?我只想打印值 So High
.
Just wanted to know if there is a possibility to read and print the value in that enum as println!("{:?}", srange::High);
, just to print out the string value?
I only want to print the value So High
.
如果我使用 srange :: High
,这将引发错误
If I use srange::High
This will throw an error saying
println!("{:?}", srange::High);
| ^^^^^^ use of undeclared type or module `srange`
error: aborting due to previous error
推荐答案
您可以在枚举上实现一种方法来提取值:
You can implement a method on your enum to extract the value:
#[derive(Debug)]
enum SalaryRange<S> {
Low(S),
Mid(S),
High(S),
}
impl<S> SalaryRange<S> {
fn value(&self) -> &S {
match self {
SalaryRange::Low(value) => value,
SalaryRange::Mid(value) => value,
SalaryRange::High(value) => value,
}
}
}
println!("{:?}", srange.value());
这篇关于如何读取与Rust中的自定义类型相关联的枚举的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!