I have a Struct with an identifier which can have 2 types of input:
- Another Struct
- Vec
pub name: String,
pub multi_type: Vec<struct B> //This could be Vec<Vec<struct B>> as well```
}
How can I achieve this?
I have a Struct with an identifier which can have 2 types of input:
pub name: String,
pub multi_type: Vec<struct B> //This could be Vec<Vec<struct B>> as well```
}
How can I achieve this?
How about an enum?
pub struct A {
name: String,
multi_type: Vec<MyEnum>,
}
enum MyEnum {
Value(A),
Vec(Vec<MyEnum>),
}
Thanks for your response!
I am getting error for this approach
pub enum C {
Type1(B),
Type2(Vec<B>)
}
pub struct B{
description: String
data: Vec<String>
}
pub struct A{
name: String
multi_type: Vec<C>
}
Error: unknown variant description, expected Type1 or Type2
This literal code, after fixing syntax errors, compiles on Playground. What's the code causing errors?
I am trying to get response from web and store it.
let data = response.json::<Vec<A>>()?;
Please post the full error.
Do you get this error on runtime? If so, the raw response text would be helpful, too. But from what I see, you probably want untagged representation of enum.
according to docs I also suggest enums.
struct MyStruct {
name: String,
age: u8,
}
struct SomeStruct {
login_count: usize,
}
enum MyEnumForMixedType {
AnotherStruct(SomeStruct),
OrAVector(Vec<MyStruct>),
OrAVecVec(Vec<Vec<MyStruct>>),
// ...
}
struct IHaveAStruct {
mixed_value: MyEnumForMixedType,
}
fn main() {
let a = MyStruct {
name: String::from("Ulvi"),
age: 35_u8,
};
let b = MyStruct {
name: String::from("John"),
age: 37_u8,
};
let c = MyStruct {
name: String::from("Mike"),
age: 32_u8,
};
let vec_a = vec![a, b, c]; // concreate vector
let d = SomeStruct { // concreate another struct
login_count: 75_usize,
};
let type1 = MyEnumForMixedType::AnotherStruct(d);
let type2 = MyEnumForMixedType::OrAVector(vec_a);
let this_struct_accepts_both = IHaveAStruct { mixed_value: type1 };
let this_struct_accepts_both2 = IHaveAStruct { mixed_value: type2 };
}