1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
| // Copyright 2025 Google LLC
// SPDX-License-Identifier: Apache-2.0
// 问题:实现一个 GUI API
// 问题:绘图 API 的最小有用行为是什么?
pub trait DrawApi {
fn arc(&self, center: [f32; 2], radius: f32, start_angle: f32, end_angle: f32);
fn line(&self, start: [f32; 2], end: [f32; 2]);
}
pub struct TextDraw;
impl DrawApi for TextDraw {
fn arc(&self, center: [f32; 2], radius: f32, start_angle: f32, end_angle: f32) {
println!("arc of radius ")
}
fn line(&self, start: [f32; 2], end: [f32; 2]) { /* ... */
}
}
// 问题:对用户而言怎样的 API 更好?
pub trait Draw {
fn draw<T: DrawApi>(&self, surface: &mut T);
}
pub struct Rect {
start: [f32; 2],
end: [f32; 2],
}
impl Draw for Rect {
fn draw<T: DrawApi>(&self, surface: &mut T) {
surface.line([self.start[0], self.start[1]], [self.end[0], self.start[1]]);
surface.line([self.end[0], self.start[1]], [self.end[0], self.end[1]]);
surface.line([self.end[0], self.end[1]], [self.start[0], self.end[1]]);
surface.line([self.start[0], self.end[1]], [self.start[0], self.start[1]]);
}
}
|