Fleet 结构体示例

结构体是 Fleet 语言中定义自定义数据类型的主要方式,采用 Rust 风格的语法。

📝 基础结构体

简单结构体定义

struct Point {
    x: int,
    y: int,
}

fn main() {
    // 创建结构体实例
    let origin = Point { x: 0, y: 0 };
    let point = Point { x: 10, y: 20 };

    // 访问字段
    print("Origin: (" + origin.x + ", " + origin.y + ")");
    print("Point: (" + point.x + ", " + point.y + ")");
}

输出

Origin: (0, 0)
Point: (10, 20)

复杂结构体

struct Person {
    name: str,
    age: int,
    email: str,
    is_active: bool,
}

fn main() {
    let person = Person {
        name: "Alice",
        age: 30,
        email: "alice@example.com",
        is_active: true,
    };

    print("Name: " + person.name);
    print("Age: " + person.age);
    print("Email: " + person.email);
    print("Active: " + person.is_active);
}

🏗️ 结构体方法

使用 Trait 为结构体添加方法

struct Rectangle {
    width: f64,
    height: f64,
}

trait Geometry {
    fn area(self) -> f64;
    fn perimeter(self) -> f64;
    fn is_square(self) -> bool;
}

impl Geometry for Rectangle {
    fn area(self) -> f64 {
        return self.width * self.height;
    }

    fn perimeter(self) -> f64 {
        return 2.0 * (self.width + self.height);
    }

    fn is_square(self) -> bool {
        return self.width == self.height;
    }
}

trait Display {
    fn show(self) -> str;
}

impl Display for Rectangle {
    fn show(self) -> str {
        return "Rectangle(" + self.width + "x" + self.height + ")";
    }
}

fn main() {
    let rect = Rectangle { width: 10.0, height: 5.0 };
    let square = Rectangle { width: 8.0, height: 8.0 };

    print(rect.show());
    print("Area: " + rect.area());
    print("Perimeter: " + rect.perimeter());
    print("Is square: " + rect.is_square());

    print("");

    print(square.show());
    print("Area: " + square.area());
    print("Is square: " + square.is_square());
}

输出

Rectangle(10.0x5.0)
Area: 50.0
Perimeter: 30.0
Is square: false

Rectangle(8.0x8.0)
Area: 64.0
Is square: true

🎯 嵌套结构体

结构体包含其他结构体

struct Address {
    street: str,
    city: str,
    country: str,
    postal_code: str,
}

struct Company {
    name: str,
    address: Address,
    employee_count: int,
}

trait Info {
    fn display_info(self);
}

impl Info for Address {
    fn display_info(self) {
        print("Address:");
        print("  " + self.street);
        print("  " + self.city + ", " + self.postal_code);
        print("  " + self.country);
    }
}

impl Info for Company {
    fn display_info(self) {
        print("Company: " + self.name);
        print("Employees: " + self.employee_count);
        self.address.display_info();
    }
}

fn main() {
    let address = Address {
        street: "123 Tech Street",
        city: "San Francisco",
        country: "USA",
        postal_code: "94105",
    };

    let company = Company {
        name: "Fleet Technologies",
        address: address,
        employee_count: 150,
    };

    company.display_info();
}

输出

Company: Fleet Technologies
Employees: 150
Address:
  123 Tech Street
  San Francisco, 94105
  USA

🔄 结构体更新语法

基于现有结构体创建新实例

struct Config {
    debug: bool,
    optimization: int,
    target: str,
    version: str,
}

trait ConfigOps {
    fn with_debug(self, debug: bool) -> Config;
    fn with_optimization(self, level: int) -> Config;
    fn show_config(self);
}

impl ConfigOps for Config {
    fn with_debug(self, debug: bool) -> Config {
        return Config {
            debug: debug,
            optimization: self.optimization,
            target: self.target,
            version: self.version,
        };
    }

    fn with_optimization(self, level: int) -> Config {
        return Config {
            debug: self.debug,
            optimization: level,
            target: self.target,
            version: self.version,
        };
    }

    fn show_config(self) {
        print("Config:");
        print("  Debug: " + self.debug);
        print("  Optimization: " + self.optimization);
        print("  Target: " + self.target);
        print("  Version: " + self.version);
    }
}

fn main() {
    let base_config = Config {
        debug: false,
        optimization: 0,
        target: "x86_64",
        version: "1.0.0",
    };

    print("Base configuration:");
    base_config.show_config();

    print("\nDebug configuration:");
    let debug_config = base_config.with_debug(true);
    debug_config.show_config();

    print("\nOptimized configuration:");
    let opt_config = base_config.with_optimization(3);
    opt_config.show_config();
}

🎮 实际应用示例

游戏角色系统

struct Stats {
    health: int,
    mana: int,
    strength: int,
    agility: int,
    intelligence: int,
}

struct Character {
    name: str,
    level: int,
    stats: Stats,
    experience: int,
}

trait CharacterOps {
    fn display_character(self);
    fn level_up(self) -> Character;
    fn take_damage(self, damage: int) -> Character;
    fn is_alive(self) -> bool;
}

impl CharacterOps for Character {
    fn display_character(self) {
        print("=== " + self.name + " ===");
        print("Level: " + self.level);
        print("Experience: " + self.experience);
        print("Health: " + self.stats.health);
        print("Mana: " + self.stats.mana);
        print("Strength: " + self.stats.strength);
        print("Agility: " + self.stats.agility);
        print("Intelligence: " + self.stats.intelligence);
        print("");
    }

    fn level_up(self) -> Character {
        let new_stats = Stats {
            health: self.stats.health + 10,
            mana: self.stats.mana + 5,
            strength: self.stats.strength + 2,
            agility: self.stats.agility + 2,
            intelligence: self.stats.intelligence + 2,
        };

        return Character {
            name: self.name,
            level: self.level + 1,
            stats: new_stats,
            experience: 0,
        };
    }

    fn take_damage(self, damage: int) -> Character {
        let new_health = self.stats.health - damage;
        let new_stats = Stats {
            health: new_health,
            mana: self.stats.mana,
            strength: self.stats.strength,
            agility: self.stats.agility,
            intelligence: self.stats.intelligence,
        };

        return Character {
            name: self.name,
            level: self.level,
            stats: new_stats,
            experience: self.experience,
        };
    }

    fn is_alive(self) -> bool {
        return self.stats.health > 0;
    }
}

fn main() {
    let initial_stats = Stats {
        health: 100,
        mana: 50,
        strength: 10,
        agility: 8,
        intelligence: 12,
    };

    let hero = Character {
        name: "Aragorn",
        level: 1,
        stats: initial_stats,
        experience: 0,
    };

    print("Initial character:");
    hero.display_character();

    print("After leveling up:");
    let leveled_hero = hero.level_up();
    leveled_hero.display_character();

    print("After taking damage:");
    let damaged_hero = leveled_hero.take_damage(25);
    damaged_hero.display_character();

    print("Is alive: " + damaged_hero.is_alive());
}

📊 数据处理示例

学生成绩管理系统

struct Grade {
    subject: str,
    score: f64,
    credits: int,
}

struct Student {
    id: str,
    name: str,
    grades: [Grade],
}

trait GradeOps {
    fn add_grade(self, grade: Grade) -> Student;
    fn calculate_gpa(self) -> f64;
    fn display_transcript(self);
}

impl GradeOps for Student {
    fn add_grade(self, grade: Grade) -> Student {
        let mut new_grades = self.grades;
        new_grades.push(grade);

        return Student {
            id: self.id,
            name: self.name,
            grades: new_grades,
        };
    }

    fn calculate_gpa(self) -> f64 {
        if self.grades.len() == 0 {
            return 0.0;
        }

        let mut total_points = 0.0;
        let mut total_credits = 0;

        loop grade in self.grades {
            total_points = total_points + (grade.score * grade.credits as f64);
            total_credits = total_credits + grade.credits;
        }

        return total_points / total_credits as f64;
    }

    fn display_transcript(self) {
        print("=== Transcript for " + self.name + " ===");
        print("Student ID: " + self.id);
        print("");

        loop grade in self.grades {
            print(grade.subject + ": " + grade.score + " (" + grade.credits + " credits)");
        }

        print("");
        print("GPA: " + self.calculate_gpa());
        print("=====================================");
    }
}

fn main() {
    let student = Student {
        id: "S12345",
        name: "Alice Johnson",
        grades: [],
    };

    let math_grade = Grade {
        subject: "Mathematics",
        score: 85.5,
        credits: 4,
    };

    let physics_grade = Grade {
        subject: "Physics",
        score: 92.0,
        credits: 3,
    };

    let cs_grade = Grade {
        subject: "Computer Science",
        score: 88.5,
        credits: 4,
    };

    let final_student = student
        .add_grade(math_grade)
        .add_grade(physics_grade)
        .add_grade(cs_grade);

    final_student.display_transcript();
}

🎯 最佳实践

1. 结构体设计原则

  • 单一职责 - 每个结构体应该有明确的职责
  • 字段命名 - 使用清晰、描述性的字段名
  • 类型选择 - 选择合适的字段类型

2. 方法组织

  • 相关方法分组 - 使用不同的 trait 组织相关方法
  • 命名约定 - 使用一致的方法命名风格
  • 返回新实例 - 对于修改操作,返回新的结构体实例

3. 性能考虑

  • 字段顺序 - 考虑内存对齐和缓存友好性
  • 避免深层嵌套 - 过深的嵌套可能影响性能
  • 合理使用引用 - 在适当的时候使用引用而不是值传递

⚠️ 注意事项

  1. 不可变性 - Fleet 中的结构体字段默认不可变
  2. Self 参数 - 方法中的 self 参数获取结构体的所有权
  3. 字段访问 - 使用点号语法访问字段:struct.field
  4. 方法调用 - 使用点号语法调用方法:struct.method()

🔗 相关文档

  • Trait 系统 - 学习如何为结构体添加方法
  • 枚举类型 - 了解另一种自定义类型
  • 模式匹配 - 结构体的模式匹配

Fleet 的结构体系统提供了强大而灵活的数据建模能力,是构建复杂应用程序的基础。