英文:
How to return a generic struct in Rust
问题
pub fn tryparse() -> (CLIAction, impl std::any::Any) {
let args = CLI::from_args();
match args.cmd {
SubCommand::Add(opt) => {
(CLIAction::QuantityAdd, Box::new(opt) as Box<dyn std::any::Any>)
}
SubCommand::Del(opt) => {
(CLIAction::QuantityDel, Box::new(opt) as Box<dyn std::any::Any>)
}
SubCommand::Search(opt) => {
(CLIAction::Search, Box::new(opt) as Box<dyn std::any::Any>)
}
}
}
英文:
Beginner in Rust, I'm wondering how to return generic data in a function.
pub fn tryparse() -> (CLIAction, ArgSingle) {
let args = CLI::from_args();
match args.cmd {
SubCommand::Add(opt) => {
(CLIAction::QuantityAdd,opt)
}
SubCommand::Del(opt) => {
(CLIAction::QuantityDel,opt)
}
}
}
In this example both Add
and Del
get a ArgSingle
struct type. However I'd like to implement a Search
that would use a ArgSearch
struct type, and return it... How to tell rust that tryparse()
can return either ArgSingle
or ArgSearch
type?
答案1
得分: 1
看起来你想要从tryparse()
函数中返回ArgSingle
或ArgSearch
。有几种方法可以做到这一点,其中一种常见的方法是使用枚举作为返回类型。
首先,定义一个枚举,表示函数可能返回的所有类型:
enum CLIResult {
Single(ArgSingle),
Search(ArgSearch),
}
然后,修改函数以在元组内返回这个枚举:
pub fn tryparse() -> (CLIAction, CLIResult) {
let args = CLI::from_args();
match args.cmd {
SubCommand::Add(opt) => {
(CLIAction::QuantityAdd, CLIResult::Single(opt))
}
SubCommand::Del(opt) => {
(CLIAction::QuantityDel, CLIResult::Single(opt))
}
SubCommand::Search(opt) => {
(CLIAction::Search, CLIResult::Search(opt))
}
}
}
现在,这个函数可以返回ArgSingle
作为CLIResult::Single
或ArgSearch
作为CLIResult::Search
。
要使用tryparse()
的返回值,你需要对CLIResult
枚举进行模式匹配,以提取适当类型的结果。例如:
let (action, result) = tryparse();
match result {
CLIResult::Single(single_arg) => {
// 处理单一参数的情况
}
CLIResult::Search(search_arg) => {
// 处理搜索参数的情况
}
}
英文:
Sounds like you want to return either ArgSingle
or ArgSearch
from tryparse()
function. There are a few approaches to that, a common one is to use enumerations as the return.
First, define an enum that represents all the possible types that can be returned from the function:
enum CLIResult {
Single(ArgSingle),
Search(ArgSearch),
}
Then, modify the function to return this enum inside of the tuple:
pub fn tryparse() -> (CLIAction, CLIResult) {
let args = CLI::from_args();
match args.cmd {
SubCommand::Add(opt) => {
(CLIAction::QuantityAdd, CLIResult::Single(opt))
}
SubCommand::Del(opt) => {
(CLIAction::QuantityDel, CLIResult::Single(opt))
}
SubCommand::Search(opt) => {
(CLIAction::Search, CLIResult::Search(opt))
}
}
}
Now, the function can return either ArgSingle
as CLIResult::Single
or ArgSearch
as CLIResult::Search
.
To use the return value of tryparse()
, you would need to pattern match on the CLIResult
enum to extract the appropriate type of result. For example:
let (action, result) = tryparse();
match result {
CLIResult::Single(single_arg) => {
// Handle single argument case
}
CLIResult::Search(search_arg) => {
// Handle search argument case
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论