This repository was archived by the owner on Aug 18, 2025. It is now read-only.
File tree Expand file tree Collapse file tree 2 files changed +127
-0
lines changed
Expand file tree Collapse file tree 2 files changed +127
-0
lines changed Original file line number Diff line number Diff line change 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+ };
Original file line number Diff line number Diff line change 1+ // 强类型系统测试
2+
3+ // 测试显式类型声明
4+ fn test_explicit_types() : void {
5+ // 显式类型声明 - 强类型语言的标准做法
6+ x: int = 42;
7+ y: float = 3.14;
8+ z: string = "Hello";
9+ b: bool = true;
10+ l: long = 1000000;
11+
12+ // 这些都是安全的,因为类型明确
13+ };
14+
15+ // 测试自动类型推断
16+ fn test_auto_inference() : void {
17+ // 自动类型推断 - 编译器推断类型,但仍然是强类型
18+ a: auto = 100; // 推断为 int
19+ b: auto = 2.71; // 推断为 float
20+ c: auto = "World"; // 推断为 string
21+ d: auto = false; // 推断为 bool
22+ e: auto = 999999; // 推断为 int (或 long,取决于实现)
23+
24+ // 复杂表达式的类型推断
25+ sum: auto = a + 50; // int + int = int
26+ product: auto = b * 2.0; // float * float = float
27+ concat: auto = c + "!"; // string + string = string
28+ };
29+
30+ // 测试类型安全 - 不允许隐式转换
31+ fn test_type_safety() : void {
32+ x: int = 42;
33+ y: float = 3.14;
34+
35+ // 在强类型语言中,这些操作需要显式转换
36+ // 不能直接混合不同类型的运算
37+
38+ // 正确的做法是使用显式转换(如果语法支持)
39+ // result: auto = x + (y as int); // 需要显式转换
40+
41+ // 或者保持类型一致
42+ int_result: auto = x + 10; // int + int = int
43+ float_result: auto = y + 1.0; // float + float = float
44+ };
45+
46+ // 主函数
47+ fn main() : void {
48+ test_explicit_types();
49+ test_auto_inference();
50+ test_type_safety();
51+ };
You can’t perform that action at this time.
0 commit comments