這個問題在這里已經有了答案: 一個方法的多個回傳型別 (1 answer) 2 天前關閉。
我是一個新手,正在嘗試通過做一個副專案來學習 Rust。我目前正在嘗試從 Rust 中的同一函式回傳多個物件型別。請看下面的例子:
// I am currently having a base structure A
pub struct A{
...
}
// three more structures uses the base structure:
pub struct B{
a: A,
s: String
}
pub struct C{
a: A,
s: String
}
pub struct D{
a: A,
s: String
}
// Now a function I am writing here which needs to return an object of any of the above mention structures i.e. an object of either B,C or D:
fn func(a:A,s:String) -> B or C or D{
return obj of B
or return obj of C
or return obj of D
}
我嘗試使用列舉,但我想我對 Rust 的熟練程度不足以使用它。我也嘗試過使用通用型別,但在那個領域仍然不是很清楚。任何幫助將不勝感激......提前致謝。
uj5u.com熱心網友回復:
使用列舉:
// your structs A, B, C, D
enum BCD {
B(B),
C(C),
D(D),
}
fn func(a:A,s:String) -> BCD {
let return_b = true;
let return_c = false;
if return_b {
BCD::B(B{ a, s })
} else if return_c {
BCD::C(C{ a, s })
} else {
BCD::D(D{ a, s })
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/537060.html
標籤:仿制药锈枚举返回结构体
