2020-04-15 03:15:30 +00:00
|
|
|
# 联合(Union)
|
2020-04-16 07:09:09 +00:00
|
|
|
|
|
|
|
联合的定义和接口非常像,**但不允许定义字段**。这两个类型的实现原理也差不多,对于`Async-graphql`来说,联合类型是接口类型的子集。
|
|
|
|
|
|
|
|
下面把接口定义的例子做一个小小的修改,去掉字段的定义。
|
|
|
|
|
|
|
|
```rust
|
|
|
|
use async_graphql::*;
|
|
|
|
|
|
|
|
struct Circle {
|
|
|
|
radius: f32,
|
|
|
|
}
|
|
|
|
|
2020-09-13 04:12:32 +00:00
|
|
|
#[GQLObject]
|
2020-04-16 07:09:09 +00:00
|
|
|
impl Circle {
|
|
|
|
async fn area(&self) -> f32 {
|
|
|
|
std::f32::consts::PI * self.radius * self.radius
|
|
|
|
}
|
|
|
|
|
|
|
|
async fn scale(&self, s: f32) -> Shape {
|
|
|
|
Circle { radius: self.radius * s }.into()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
struct Square {
|
|
|
|
width: f32,
|
|
|
|
}
|
|
|
|
|
2020-09-13 04:12:32 +00:00
|
|
|
#[GQLObject]
|
2020-04-16 07:09:09 +00:00
|
|
|
impl Square {
|
|
|
|
async fn area(&self) -> f32 {
|
|
|
|
self.width * self.width
|
|
|
|
}
|
|
|
|
|
|
|
|
async fn scale(&self, s: f32) -> Shape {
|
|
|
|
Square { width: self.width * s }.into()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-09-13 04:12:32 +00:00
|
|
|
#[derive(GQLUnion)]
|
2020-05-11 04:39:43 +00:00
|
|
|
enum Shape {
|
|
|
|
Circle(Circle),
|
|
|
|
Square(Square),
|
|
|
|
}
|
|
|
|
```
|