Rust में सामान्य ट्रेट को लागू करने वाले ऑब्जेक्ट्स का वेक्टर: कैसे बनाएं और उपयोग करें?
नमस्ते! मैं Rust में नया हूँ और पॉलीमॉर्फिज़्म को समझने की कोशिश कर रहा हूँ। मेरे पास `Shape` नामक एक trait है जिसमें `area()` method है, और कई structs (`Circle`, `Rectangle`) हैं जो इसे implement करते हैं। मैं एक ऐसा vector बनाना चाहता हूँ जो इस trait को implement करने वाले विभिन्न प्रकार के objects को store कर सके।
C++ या Java में मैं कुछ ऐसा लिखता: `vector shapes;` या `List shapes = new ArrayList<>();`। लेकिन Rust में मैं सीधे `Vec` नहीं लिख सकता — compiler कहता है कि trait का size compile time पर ज्ञात नहीं है।
यहाँ मेरा कोड है जो काम नहीं करता:
```rust
trait Shape {
fn area(&self) -> f64;
}
struct Circle {
radius: f64,
}
impl Shape for Circle {
fn area(&self) -> f64 {
std::f64::consts::PI * self.radius * self.radius
}
}
struct Rectangle {
width: f64,
height: f64,
}
impl Shape for Rectangle {
fn area(&self) -> f64 {
self.width * self.height
}
}
fn main() {
// यह काम नहीं करेगा:
// let shapes: Vec = vec![
// Circle { radius: 5.0 },
// Rectangle { width: 3.0, height: 4.0 },
// ];
}
```
मैं ऐसा vector कैसे बना सकता हूँ जो विभिन्न प्रकार के objects को store करे, जो सभी `Shape` trait को implement करते हों?