Data structures 如何在特征函数中发送不同的结构? enum属性{ 三角形(三角形属性), 平方(平方属性), } 结构三角形{ x:u8, y:Vec, } 结构广场{ x:u8, y:弦, } 结构三角形属性{ 答:u8, b:u8, c:u8, } 结构平方属性{ 答:u8, b:u8, c:u8, d:u8, } 性状形状{ fn do_magic(&self,p:Property)->u64; } 三角形的impl形{ fn do_magic(&self,p:Property)->u64{ 比赛(p){ 三角形(x)=>{/*用x*/} _=>恐慌(“这不会发生”), } } } 正方形的impl形状{ fn do_magic(&self,p:Property)->u64{ 比赛(p){ 平方(x)=>{/*用x*/} _=>恐慌(“这不会发生”), } } }
正如你所看到的,我正在呼叫Data structures 如何在特征函数中发送不同的结构? enum属性{ 三角形(三角形属性), 平方(平方属性), } 结构三角形{ x:u8, y:Vec, } 结构广场{ x:u8, y:弦, } 结构三角形属性{ 答:u8, b:u8, c:u8, } 结构平方属性{ 答:u8, b:u8, c:u8, d:u8, } 性状形状{ fn do_magic(&self,p:Property)->u64; } 三角形的impl形{ fn do_magic(&self,p:Property)->u64{ 比赛(p){ 三角形(x)=>{/*用x*/} _=>恐慌(“这不会发生”), } } } 正方形的impl形状{ fn do_magic(&self,p:Property)->u64{ 比赛(p){ 平方(x)=>{/*用x*/} _=>恐慌(“这不会发生”), } } },data-structures,struct,enums,rust,traits,Data Structures,Struct,Enums,Rust,Traits,正如你所看到的,我正在呼叫恐慌,我认为这不是解决这个问题的好方法 这只是一个示例,但我不能在Triangle结构中包含TriangleProperty。因为我正在使用TriangleProperty作为函数do_magic的输入,该函数使用常量不可变Trianglestruct。因此,我能想到的唯一选择是在enum中包装。但是有更好的方法吗?这看起来像是关联类型的用例: 当您实现Shape时,您可以选择Self::Property的类型,并且在impl中可以将其用作具体类型。编译器将不允许您将S
恐慌
,我认为这不是解决这个问题的好方法
这只是一个示例,但我不能在
Triangle
结构中包含TriangleProperty
。因为我正在使用TriangleProperty
作为函数do_magic
的输入,该函数使用常量不可变Triangle
struct。因此,我能想到的唯一选择是在enum
中包装。但是有更好的方法吗?这看起来像是关联类型的用例:
当您实现Shape
时,您可以选择Self::Property
的类型,并且在impl
中可以将其用作具体类型。编译器将不允许您将SquareProperty
传递给Triangle::do_magic
或反之亦然
enum Property {
Triangle(TriangleProperty),
Square(SquareProperty),
}
struct Triangle {
x: u8,
y: Vec<u8>,
}
struct Square {
x: u8,
y: String,
}
struct TriangleProperty {
a: u8,
b: u8,
c: u8,
}
struct SquareProperty {
a: u8,
b: u8,
c: u8,
d: u8,
}
trait Shape {
fn do_magic(&self, p: Property) -> u64;
}
impl Shape for Triangle {
fn do_magic(&self, p: Property) -> u64 {
match (p) {
Triangle(x) => { /* do something with x */ }
_ => panic("this wont happen"),
}
}
}
impl Shape for Square {
fn do_magic(&self, p: Property) -> u64 {
match (p) {
Square(x) => { /* do something with x */ }
_ => panic("this wont happen"),
}
}
}
trait Shape {
type Property;
fn do_magic(&self, p: Self::Property) -> u64;
}
impl Shape for Triangle {
type Property = TriangleProperty;
fn do_magic(&self, p: Self::Property) -> u64 {
/* do something with p */
}
}
impl Shape for Square {
type Property = SquareProperty;
fn do_magic(&self, p: Self::Property) -> u64 {
/* do something with p */
}
}