Skip to content
This repository was archived by the owner on Aug 18, 2025. It is now read-only.

Commit cbe1e5e

Browse files
committed
新增泛型功能测试示例,包括泛型函数、类、枚举、接口及带约束的泛型函数,增强了泛型系统的测试覆盖。
1 parent 0eb8c0b commit cbe1e5e

File tree

1 file changed

+76
-0
lines changed

1 file changed

+76
-0
lines changed

test_generics.cn

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
// 测试泛型功能的示例代码
2+
3+
// 泛型函数示例
4+
fn max<T>(a: T, b: T) : T {
5+
if (a > b) {
6+
return a;
7+
} else {
8+
return b;
9+
};
10+
};
11+
12+
// 泛型类示例
13+
class Container<T> {
14+
private T value;
15+
16+
constructor(T initial_value) {
17+
this.value = initial_value;
18+
};
19+
20+
fn get<T>() : T {
21+
return this.value;
22+
};
23+
24+
fn set<T>(T new_value) : void {
25+
this.value = new_value;
26+
};
27+
};
28+
29+
// 泛型枚举示例
30+
enum Option<T> {
31+
Some(T value),
32+
None
33+
};
34+
35+
// 泛型接口示例
36+
interface Comparable<T> {
37+
fn compare(T other) : int;
38+
};
39+
40+
// 使用泛型的函数
41+
fn test_generics() : void {
42+
// 测试泛型函数调用
43+
let int_max = max<int>(10, 20);
44+
let float_max = max<float>(3.14, 2.71);
45+
46+
// 测试泛型对象创建
47+
let int_container = new Container<int>(42);
48+
let string_container = new Container<string>("Hello");
49+
50+
// 测试泛型方法调用
51+
let value = int_container.get<int>();
52+
int_container.set<int>(100);
53+
54+
// 测试泛型枚举
55+
let some_value = Option<int>::Some(42);
56+
let none_value = Option<int>::None;
57+
58+
// 测试类型转换
59+
let converted = value as float;
60+
61+
// 测试类型查询
62+
let type_info = typeof(value);
63+
64+
print("泛型测试完成");
65+
};
66+
67+
// 带约束的泛型函数
68+
fn sort<T: Comparable<T>>(array<T> items) : array<T> where T: Copy {
69+
// 简单的排序实现
70+
return items;
71+
};
72+
73+
// 主函数
74+
fn main() : void {
75+
test_generics();
76+
};

0 commit comments

Comments
 (0)