Method, device and equipment for rust language inheritance and method override

CN122945937APending Publication Date: 2026-10-20GUANGZHOU AVA ELECTRONICS TECH CO LTD
View PDF 0 Cites 0 Cited by

Patent Information

Application Number
CN202611280250.4
Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
Filing Date
2026-08-22
Publication Date
2026-10-20

AI Technical Summary

Technical Problem

这些现有方案存在组合型子类型样板代码爆炸、模板方法无法正确回调子类重写版本、工程不可维护、丧失开闭原则与多态容器能力等不足

Benefits of technology

[0015]本发明中,通过在Rust语言中建立对外能力trait、策略trait、AsRef桥接和Blanket Implementation的协同机制,能够在无继承语法的前提下系统化复现Java的interface默认方法、abstract class扩展、子类方法重写以及模板方法在运行时命中子类重写版本等面向对象继承语义,同时支持异构trait object容器,避免了为每个组合子类型手写大量转发代码的问题,显著降低了样板代码量,提高了代码的可维护性和可扩展性;通过host_slot与循环Arc构造解决了策略先创建、宿主后成型的循环依赖问题,保证了模板方法在运行时能够正确命中子类重写版本;通过构造期策略注入并禁止运行时替换,使行为可预测、利于审计与测试。

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure FT_1
    Figure FT_1
  • Figure FT_2
    Figure FT_2
Patent Text Reader

Abstract

This invention discloses a method, apparatus, and device for inheritance and method overriding in the Rust language. The method includes: defining an external capability trait and setting a default method; obtaining a host struct through AsRef conversion and calling the implementation method; extracting a strategy trait for the method to be overridden, allowing the host struct to hold the strategy trait via a pointer; establishing an AsRef bridge and using Blanket Implementation to automatically obtain the external capability trait from the outer composite type; injecting a strategy instance during the construction phase to implement method overriding; establishing a host slot and resolving circular dependencies using a circular Arc constructor; and placing different concrete types into a heterogeneous polymorphic container and dynamically distributing them. This invention can reproduce object-oriented inheritance semantics in Rust without inheritance syntax.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This invention relates to the field of computer programming language technology, and more specifically, to a method, apparatus, and device for inheritance and method overriding in the Rust language. Background Technology

[0002] Rust is a modern systems programming language that combines memory safety, high performance, and concurrency safety, and is widely used in systems development, network programming, and embedded devices.

[0003] Rust provides interfaces and runtime polymorphism through traits and trait objects, but deliberately does not offer Java-style single inheritance hierarchy and method overriding. Existing technologies typically use pure trait inheritance and manual implementation, enumerations and pattern matching, field copying to simulate inheritance, trait objects without default method chains, or runtime modifications to closures and function pointers to replace object-oriented inheritance semantics. These existing solutions suffer from drawbacks such as boilerplate code explosion for composite subtypes, template methods failing to correctly call back overridden subclass versions, unmaintainable projects, and loss of the open / closed principle and polymorphic container capabilities. Specifically, composite subtypes cannot automatically inherit parent type interface implementations; template methods require strategies to hold host references, creating circular dependencies based on the host's construction order; if each capability is implemented manually, the project becomes unmaintainable; and if pattern matching is used for specific types, open / closed principles and polymorphic container capabilities are lost. Furthermore, there is a lack of unified rules for determining the use of mixed interface and abstract capabilities, and the constraint propagation of generic hosts and the expression of shared ownership also increase implementation complexity. Summary of the Invention

[0004] To address the challenge of systematically reproducing Java's default interface methods, abstract class extensions, subclass method overriding, and template methods hitting subclass overridden versions at runtime in Rust without inheritance syntax, and to support heterogeneous trait object containers, while avoiding the technical problem of manually writing a large number of forwards for each composite subtype, this invention provides a method, apparatus, and device for inheritance and method overriding in the Rust language. The technical solution adopted by this invention is as follows.

[0005] Firstly, this invention provides a method for inheritance and method overriding in the Rust language, including: Define an external capability trait and set a default method in the external capability trait. The default method obtains the corresponding host structure through AsRef conversion and calls the implementation method in the host structure. For methods that need to be rewritten by different combination types, extract the corresponding strategy traits respectively, and make the host structure hold the currently effective strategy trait through a pointer; Establish an AsRef bridge relationship between the outer composite type and the inner host structure, and use BlanketImplementation to enable the outer composite type that meets the AsRef constraint to automatically obtain the corresponding external capability trait; During the object construction phase, a strategy instance is injected into the host structure, enabling the composite type of subtype semantics to implement method rewriting by replacing part of the strategy instance, and allowing the unreplaced strategy instance to use the default implementation method of the host structure; When a strategy instance needs to call an implementation method on a host structure that has not yet been constructed, a shared, variable host slot, host_slot, is created, and the real host structure is written into the host_slot using a loop-based Arc constructor. Different specific types that have been constructed are placed into a heterogeneous polymorphic container in the form of external capability traits, and the corresponding strategy instances are invoked through dynamic dispatch of external capability traits.

[0006] In one implementation, the process of having the host structure hold the currently effective policy trait via a pointer includes: The host structure holds the corresponding strategy trait in the Arc field, and the corresponding method is overridden by replacing the strategy trait.

[0007] In one implementation, the host structure holds a corresponding strategy trait in the Arc field, and the process of rewriting the corresponding method by replacing the strategy trait includes: The logic that is easily rewritten is extracted as a strategy trait, and the host holds `Arc`. <dynxxx>`, where XXX is the name of the strategy trait.

[0008] In one implementation, the external capability trait includes: The first capability trait declares the first and second methods; The second ability trait combines the first ability trait with the third ability trait, and declares the third method and the fourth method; The third capability trait declares the fifth method.

[0009] In one implementation, the process of establishing an AsRef bridge relationship from the outer composite type to the inner host structure, and automatically obtaining the corresponding external capability trait for the outer composite type that satisfies the AsRef constraint through Blanket Implementation, includes: Through generic constraints and Blanket Implementation, any outer composite type that satisfies the AsRef conversion constraint automatically obtains the default method implementation of the corresponding external capability trait; The outer composite type automatically generates a multi-layer AsRef forwarding chain through macro annotations to realize the reference conversion from the outer composite type to the inner host structure.

[0010] In one implementation, the composite type of the subtype semantics is an outer composite type, which holds the inner host structure only through pointer references without copying the fields of the inner host structure; during the object construction phase, the outer composite type rewrites the corresponding methods by replacing some strategy instances, and the unreplaced strategy instances follow the default implementation method of the inner host structure, and the strategy instances are not replaced after the object construction is completed.

[0011] In one implementation, the process of establishing a shared, variable host slot (host_slot) includes: A shared variable slot is generated by annotating the constructor, and the shared variable slot is passed into the constructor of the strategy instance, so that the strategy instance reserves a host reference during the registration phase. The process of using a loop to construct and write the real host structure into the host_slot includes: During the construction phase, the real host structure is written into the shared variable slot by using the new_cyclic method of the smart pointer with circular references, so that the strategy instance automatically obtains a valid host reference after construction is completed.

[0012] Secondly, the present invention provides an apparatus for inheritance and method overriding in the Rust language, comprising: The external capability definition module is used to define external capability traits and set default methods in the external capability traits. The default methods are then converted to obtain the corresponding host structure through AsRef conversion and call the implementation methods in the host structure. The strategy extraction module is used to extract the corresponding strategy traits for methods that need to be rewritten by different combination types, and to make the host structure hold the currently effective strategy trait through a pointer; The bridging module is used to establish an AsRef bridging relationship between the outer composite type and the inner host structure, and through Blanket Implementation, the outer composite type that meets the AsRef constraint automatically obtains the corresponding external capability trait. The strategy injection module is used to inject strategy instances into the host structure during the object construction phase, so that the composite type of subtype semantics can implement method rewriting by replacing some strategy instances, and the unreplaced strategy instances can use the default implementation method of the host structure. The loop constructor module is used to create a shared, variable host slot (host_slot) when a strategy instance needs to call an implementation method on a host structure that has not yet been constructed, and to write the real host structure into the host_slot using the loop Arc constructor. The polymorphic container module is used to put different constructed specific types into the heterogeneous polymorphic container in the form of external capability traits, and to call the corresponding strategy instance through dynamic dispatch of external capability traits.

[0013] Thirdly, the present invention provides a computer device including a memory, a processor, and a computer program stored in the memory and executable on the processor, wherein the processor executes the program to implement the method of any of the above embodiments.

[0014] Fourthly, the present invention provides a computer-readable storage medium having a computer program stored thereon, characterized in that the program, when executed by a processor, implements the method of any of the above embodiments.

[0015] This invention establishes a collaborative mechanism in Rust that integrates external capability traits, strategy traits, AsRef bridging, and Blanket Implementation. This mechanism systematically reproduces Java's object-oriented inheritance semantics, such as default interface methods, abstract class extensions, subclass method overriding, and template methods hitting subclass overridden versions at runtime, without requiring inheritance syntax. It also supports heterogeneous trait object containers, avoiding the need to manually write extensive forwarding code for each composite subtype, significantly reducing boilerplate code and improving maintainability and scalability. The use of host_slot and circular Arc constructors solves the circular dependency problem of strategy creation before host implementation, ensuring that template methods correctly hit subclass overridden versions at runtime. Furthermore, by injecting strategies during construction and prohibiting runtime replacement, the behavior becomes predictable and facilitates auditing and testing. Attached Figure Description

[0016] Figure 1 This is a schematic diagram of the overall process of one of the embodiments of the present invention.

[0017] Figure 2 This is a schematic diagram of the overall structure of an embodiment of the second embodiment of the present invention. Detailed Implementation

[0018] Exemplary embodiments of the present disclosure will now be described in more detail with reference to the accompanying drawings. While exemplary embodiments of the present disclosure are shown in the drawings, it should be understood that the present disclosure may be implemented in various forms and should not be limited to the embodiments set forth herein. Rather, these embodiments are provided so that this disclosure will be thorough and complete, and will fully convey the scope of the disclosure to those skilled in the art.

[0019] It should be noted that the terms "first, second, ..." used in the embodiments of the present invention are merely used to distinguish similar objects and do not represent a specific ordering of objects. It is understood that "first, second, ..." can be interchanged in a specific order or sequence where permissible. It should be understood that the objects distinguished by "first, second, ..." can be interchanged where appropriate so that the embodiments of the present invention described herein can be implemented in an order other than those illustrated or described herein. Example 1

[0020] Please see Figure 1 , Figure 1 This is a flowchart illustrating a method for inheritance and method overriding in Rust language according to Embodiment 1 of the present invention. The method includes steps S110, S120, S130, S140, S150, and S160. It should be noted that steps S110, S120, S130, S140, S150, and S160 are merely reference numerals used to clearly explain the embodiment and the accompanying drawings. Figure 1 The correspondence is not intended to limit the order of steps in this embodiment.

[0021] Step S110: Define an external capability trait and set a default method in the external capability trait, so that the default method obtains the corresponding host structure through AsRef conversion and calls the implementation method in the host structure; Step S120: For methods that need to be rewritten by different combination types, extract the corresponding policy traits respectively, and make the host structure hold the currently effective policy trait through a pointer; Step S130: Establish an AsRef bridge relationship between the outer composite type and the inner host structure, and enable the outer composite type that satisfies the AsRef constraint to automatically obtain the corresponding external capability trait through Blanket Implementation; Step S140: During the object construction phase, inject strategy instances into the host structure so that the composite type of subtype semantics can implement method rewriting by replacing part of the strategy instances, and make the unreplaced strategy instances use the default implementation method of the host structure. Step S150: When a strategy instance needs to call an implementation method on a host structure that has not yet been constructed, a shared and variable host slot host_slot is established, and the real host structure is written into the host_slot using a loop Arc constructor. Step S160: The constructed different specific types are placed into the heterogeneous polymorphic container in the form of external capability traits, and the corresponding strategy instance is called by dynamically distributing the external capability traits.

[0022] In this method, step S110 establishes external capability interfaces (contracts) and provides default methods on the traits: for example, defining external traits for business domains (Human, Student, Complete, etc.): -`HumanLike <t>`: Declare `use_tools()` and `think()`, and write the default implementation in the trait, and call `self.as_ref().use_tools_impl()` / `think_impl()`; -`StudentLike <t>`: Semantic composition of `Complete + HumanLike` <t>Added functions like `attend_class()` and `do_homework()`, and the default method is redirected to the `Student` host. _impl`; -`Complete`: Lightweight interface type, default method calls `CompleteImpl::complete_impl()`.

[0023] In this embodiment, the external capability trait includes: a first capability trait (such as a human domain capability trait), a second capability trait (such as a student domain capability trait), and a third capability trait (such as a completion capability trait); wherein, the human domain capability trait declares a first method (such as a think method) and a second method (such as a use_tools method), the student domain capability trait combines the human domain capability trait with the completion capability trait and declares a third method (such as an attend_class method) and a fourth method (such as a do_homework method), and the completion capability trait declares a fifth method (such as a complete method).

[0024] The default method in the external capability trait does not directly execute business logic. Instead, it obtains the corresponding host structure through AsRef reference conversion and then calls the use_tools method, think method, attend_class method, do_homework method, or complete method in the host structure.

[0025] In step S110, both the default method of an interface and the concrete method of an abstract class in Java can provide a unified entry point in the parent layer. Rust traits also support default methods; by centralizing the "external API" on the trait, the caller only targets `dyn HumanLike` / `dyn StudentLike`, consistent with Java's parent-type programming. Internal execution details are pushed down to the host struct's `...` `_impl` makes it easy to mount replaceable strategies at the host layer.

[0026] Step S120: Extract the easily rewriteable logic into a policy trait (Behavior), and the host holds `Arc`. <dynbehavior>` Define a strategy trait in `behavior.rs` for each method that may be overridden multiple times, for example: -`ThinkBehavior` / `UseToolsBehavior <t>(Human Domain); -`HomeworkBehavior` / `AttendClassBehavior` (student domain); -`CompleteBehavior` (Complete Behavior).

[0027] The host struct starts with `Arc`<dyn XxxBehavior> The field holds an instance of the currently active policy. Type aliases include `Thinker = Arc`.<dyn ThinkBehavior> Simplify field declarations.

[0028] In this embodiment, the policy trait includes at least one of ThinkBehavior, UseToolsBehavior, HomeworkBehavior, AttendClassBehavior, and CompleteBehavior. The host structure holds the corresponding policy instance with the Arc field and implements the rewriting of the corresponding method by replacing the policy instance.

[0029] In this way, Rust has no vtable inheritance chain with subclasses. The "overridable method body" is separated from the struct into an independent strategy object, making "overriding = constructor-time replacement of strategy pointer," semantically aligned with Java's `@Override`, and avoiding type branches like `if type == Pupil` in business logic. Stable, never-overridden methods can be directly written in the host's `vtable`. In `_impl`, there is no need to add indirection.

[0030] Step S130: Using Blanket Implementation + AsRef bridging, eliminate duplicate impl templates and write Blanket impl for any type `V` that satisfies the constraints, for example: rust impl<T, V> StudentLike <t>for V where T: Display + Clone + 'static + Send + Sync, V: HumanLike <t>+ AsRef<Student <t>> + StudentProperty <t>+ Complete, {} ``` Outer composite types (such as `Pupil`) are accessed via `#[as_ref(Student)` <string>, student)]`、`#[as_ref(Human <string>, student, Student <string>Macros such as `AsRefBridges` automatically generate multi-layered `AsRef` forwarding chains.

[0031] In Java, subclasses automatically inherit from the parent class's interface. In Rust, manually writing `impl Complete for Pupil` and `impl StudentLike for Pupil` would result in a lot of repetitive code. Blanket impl allows "as long as `AsRef` can bridge to the inner host, the outer layer automatically has trait capabilities," enabling composable subtypes (Pupil holds `Arc`). <student>There is no need to repeatedly implement the forwarding logic.

[0032] Step S140: Abstract-type polymorphism – taking Student / Pupil as an example.

[0033] Student Host Structure: 1. Combining `Arc` <Human <t>>` (Connecting to the human domain think / use_tools); 2. Combining `Arc` <completeimpl>(Capability to complete). 3. Holds local domain policies such as `_homeworker` and `_attender`; 4. The default method for `StudentLike` is uniformly converted to `AsRef`. <Student <t>>` Take host and call` _impl`.

[0034] Pupil host structure: 1. Only holding `Arc` <Student <string>>`, do not copy the Student field; 2. Replace `thinker(PupilThink)`, `homeworker(PupilHomework)`, and `completer(PupilComplete)` when constructing Student in `Pupil::builder()`; 3. Unreplaced `attender` and other strategies retain the Student default.

[0035] This pattern corresponds to Java's `abstract class Student extends Human` and `class Pupil extends Student`. Rust uses composition instead of extends, and the subtype only changes the strategy that needs to be overridden in the constructor chain. The default behavior automatically uses the inner Student class, avoiding field duplication and deep copying.

[0036] Step S150: Template method and host_slot — resolving the circular dependency of "strategy created first, host formed later".

[0037] When the implementation of `UseToolsBehavior` needs to call `Arc` within `use_tools`. <Student <t>> on the `think()`, `student_id()`, etc. (template method semantics), while the construction order of Student is: 1. First, create the Human instance and its `use_toolser` policy; 2. At this time, `Arc` <Student <t>>` does not exist yet; 3. However, the strategy already requires holding a host reference.

[0038] This invention employs a "host_slot + loop Arc constructor": 1. `#[builder(new_cyclic_host_slot)]` generates `StudentBuilder::host_slot()`, which returns a shared, variable slot; 2. Pass `StudentUseToolsAny::new(host_slot.clone())` to the same `host_slot`; 3. During `build()`, `Arc::new_cyclic` will actually convert `Arc` to `Arc`. <Student <t>>Write to the slot; 4.`#[bind_host_strategy(host = Student <t>, strategy =StudentUseToolsAny, trait_path = UseToolsBehavior <t>The free function `fn use_tools(this: Arc)` will be used. <Student <t>>)` is bound to the strategy implementation.

[0039] This is similar to the problem in Java where `this` is not yet fully available during the constructor, but template methods need to call back overridable methods at runtime. `host_slot` allows the strategy to "reserve" host references during the registration phase, automatically taking effect after the build is complete. When `pupil.use_tools()` is called, the internal `this.think()` is dispatched via the trait's default method and the currently bound `PupilThink` strategy, achieving a cross-hit of "Student version of use_tools + Pupil version of think," without the need for hard-coded type checks.

[0040] Then, during construction, a strategy is injected to prevent runtime modification of the vtable. Strict convention: All overrides are completed in `new()` / `builder()`, and `Arc` is not replaced at runtime.<dyn Behavior> `.

[0041] Typical Pupil construction chain: rust Student::builder("Zhang San".to_string()) .human( Human::builder("Zhang San".to_string()) .thinker(PupilThink::new()) / / override think .build(), ) .complete( CompleteImpl::builder() .completer(PupilComplete::new()) / / override complete .build(), ) .homeworker(PupilHomework::new()) / / override do_homework .build() ``` This aligns with Java's fixed method dispatch table after object construction. Construction-time binding makes behavior predictable, facilitates auditing and testing; the caller only needs to call `Pupil::new()`, without needing to know the underlying strategy type, reducing API leakage.

[0044] Finally, runtime heterogeneous polymorphic containers Concrete types such as `Student` and `Pupil` are placed into the array using `Arc::clone` and coercion: rust let learners: Vec <Arc<dyn StudentLike <string>>> = vec![Student::new(), Pupil::new()]; for s in &learners { s.attend_class(); s.do_homework();

[0045] } ``` corresponding Java `List <student>Mixed-class instances. The Trait object virtual table is bound to the strategy of each object at construction time, and dynamically dispatches to the correct override version in the loop, without the need to enumerate the specific type.

[0046] This approach establishes a collaborative mechanism in Rust involving external capability traits, strategy traits, AsRef bridging, and Blanket Implementation. This allows for the systematic reproduction of Java's default interface methods, abstract class extensions, subclass method overriding, and runtime matching of subclass overridden versions by template methods, all without the need for inheritance syntax. It also supports heterogeneous trait object containers, avoiding the need to manually write extensive forwarding code for each composite subtype, significantly reducing boilerplate code and improving maintainability and scalability. The use of host_slot and circular Arc constructors resolves the circular dependency problem of strategy creation before host implementation, ensuring that template methods correctly match subclass overridden versions at runtime. Furthermore, by injecting strategies during construction and prohibiting runtime replacement, the approach makes behavior predictable and facilitates auditing and testing. Example 2

[0047] Corresponding to the method in Example 1, such as Figure 2 As shown, Figure 2 This is a schematic diagram of the overall structure of an embodiment of the present invention. The present invention also provides a Rust language inheritance and method overriding device 2, including: an external capability definition module 210, a strategy extraction module 220, a bridging module 230, a strategy injection module 240, a loop construction module 250, and a polymorphic container module 260.

[0048] The external capability definition module 210 is used to define external capability traits and set default methods in the external capability traits, so that the default methods obtain the corresponding host structure through AsRef conversion and call the implementation methods in the host structure; The strategy extraction module 220 is used to extract the corresponding strategy traits for methods that need to be rewritten by different combination types, and to make the host structure hold the currently effective strategy trait through a pointer; The bridging module 230 is used to establish an AsRef bridging relationship between the outer composite type and the inner host structure, and to enable the outer composite type that meets the AsRef constraint to automatically obtain the corresponding external capability trait through Blanket Implementation; The strategy injection module 240 is used to inject strategy instances into the host structure during the object construction phase, so that the composite type of subtype semantics can implement method rewriting by replacing part of the strategy instances, and the unreplaced strategy instances can use the default implementation method of the host structure. The loop constructor module 250 is used to create a shared, variable host slot host_slot when the strategy instance needs to call the implementation method on the host structure that has not yet been constructed, and to write the real host structure into the host_slot using the loop Arc constructor. The polymorphic container module 260 is used to put different constructed specific types into the heterogeneous polymorphic container in the form of external capability traits, and to call the corresponding strategy instance through dynamic dispatch of external capability traits.

[0049] In one implementation, the process of having the host structure hold the currently effective policy trait via a pointer includes: The host structure holds the corresponding strategy trait in the Arc field, and the corresponding method is overridden by replacing the strategy trait.

[0050] In one implementation, the host structure holds a corresponding strategy trait in the Arc field, and the process of rewriting the corresponding method by replacing the strategy trait includes: The logic that is easily rewritten is extracted as a strategy trait, and the host holds `Arc`. <dynxxx>`, where XXX is the name of the strategy trait.

[0051] In one implementation, the external capability trait includes: The first capability trait declares the first and second methods; The second ability trait combines the first ability trait with the third ability trait, and declares the third method and the fourth method; The third capability trait declares the fifth method.

[0052] In one implementation, the process of establishing an AsRef bridge relationship from the outer composite type to the inner host structure, and automatically obtaining the corresponding external capability trait for the outer composite type that satisfies the AsRef constraint through Blanket Implementation, includes: Through generic constraints and Blanket Implementation, any outer composite type that satisfies the AsRef conversion constraint automatically obtains the default method implementation of the corresponding external capability trait; The outer composite type automatically generates a multi-layer AsRef forwarding chain through macro annotations to realize the reference conversion from the outer composite type to the inner host structure.

[0053] In one implementation, the composite type of the subtype semantics is an outer composite type, which holds the inner host structure only through pointer references without copying the fields of the inner host structure; during the object construction phase, the outer composite type rewrites the corresponding methods by replacing some strategy instances, and the unreplaced strategy instances follow the default implementation method of the inner host structure, and the strategy instances are not replaced after the object construction is completed.

[0054] In one implementation, the process of establishing a shared, variable host slot (host_slot) includes: A shared variable slot is generated by annotating the constructor, and the shared variable slot is passed into the constructor of the strategy instance, so that the strategy instance reserves a host reference during the registration phase. The process of using a loop to construct and write the real host structure into the host_slot includes: During the construction phase, the real host structure is written into the shared variable slot by using the new_cyclic method of the smart pointer with circular references, so that the strategy instance automatically obtains a valid host reference after construction is completed.

[0055] In this device, by establishing a collaborative mechanism in the Rust language for external capability traits, policy traits, AsRef bridging, and Blanket Implementation, it can systematically reproduce Java's object-oriented inheritance semantics, such as default interface methods, abstract class extensions, subclass method overriding, and template methods hitting subclass overridden versions at runtime, without inheritance syntax. It also supports heterogeneous trait object containers, avoiding the problem of manually writing a large amount of forwarding code for each composite subtype, significantly reducing boilerplate code and improving code maintainability and scalability. The host_slot and circular Arc constructor solve the circular dependency problem of policy creation before host implementation, ensuring that template methods correctly hit subclass overridden versions at runtime. Through constructor-time policy injection and prohibition of runtime replacement, behavior is predictable and facilitates auditing and testing. Example 3

[0056] This invention also provides a storage medium storing computer instructions that, when executed by a processor, implement the Rust language inheritance and method overriding methods of any of the above embodiments.

[0057] Those skilled in the art will understand that all or part of the steps of the above method embodiments can be implemented by hardware related to program instructions. The aforementioned program can be stored in a computer-readable storage medium. When the program is executed, it performs the steps of the above method embodiments. The aforementioned storage medium includes various media capable of storing program code, such as mobile storage devices, random access memory (RAM), read-only memory (ROM), magnetic disks, or optical disks.

[0058] Alternatively, if the integrated units of the present invention are implemented as software functional modules and sold or used as independent products, they can also be stored in a computer-readable storage medium. Based on this understanding, the technical solutions of the embodiments of the present invention, or the parts that contribute to related technologies, can be embodied in the form of a software product. This computer software product is stored in a storage medium and includes several instructions to cause a computer device (which may be a personal computer, terminal, or network device, etc.) to execute all or part of the methods of the various embodiments of the present invention. The aforementioned storage medium includes various media capable of storing program code, such as mobile storage devices, RAM, ROM, magnetic disks, or optical disks.

[0059] Corresponding to the computer storage medium described above, one embodiment also provides a computer device, which includes a memory, an encoder, and a computer program stored in the memory and executable on the encoder, wherein the encoder executes the program to implement any of the Rust language inheritance and method overriding methods described in the above embodiments and / or the Rust language inheritance and method overriding methods.

[0060] The aforementioned computer equipment, through the establishment of a collaborative mechanism in the Rust language for external capability traits, policy traits, AsRef bridging, and Blanket Implementation, can systematically reproduce Java's object-oriented inheritance semantics, such as default interface methods, abstract class extensions, subclass method overriding, and template methods hitting subclass overridden versions at runtime, without inheritance syntax. It also supports heterogeneous trait object containers, avoiding the problem of manually writing a large amount of forwarding code for each composite subtype, significantly reducing boilerplate code and improving code maintainability and scalability. The host_slot and circular Arc constructor solve the circular dependency problem of policy creation before host implementation, ensuring that template methods correctly hit subclass overridden versions at runtime. Through constructor-time policy injection and prohibition of runtime replacement, behavior is predictable and facilitates auditing and testing.

[0061] The technical features of the above embodiments can be combined in any way. For the sake of brevity, not all possible combinations of the technical features in the above embodiments are described. However, as long as there is no contradiction in the combination of these technical features, they should be considered to be within the scope of this specification.

[0062] Obviously, the above embodiments of the present invention are merely examples for clearly illustrating the present invention, and are not intended to limit the implementation of the present invention. Those skilled in the art can make other variations or modifications based on the above description. It is neither necessary nor possible to exhaustively describe all embodiments here. Any modifications, equivalent substitutions, and improvements made within the spirit and principles of the present invention should be included within the scope of protection of the claims of the present invention.< / dynxxx> < / student> < / string> < / t> < / t> < / t> < / t> < / t> < / t> < / string> < / t> < / completeimpl> < / t> < / student> < / string> < / string> < / string> < / t> < / t> < / t> < / t> < / t> < / dynbehavior> < / t> < / t> < / t> < / dynxxx>

Claims

1. A method for inheritance and method overriding in the Rust language, characterized in that, include: Define an external capability trait and set a default method in the external capability trait. The default method obtains the corresponding host structure through AsRef conversion and calls the implementation method in the host structure. For methods that need to be rewritten by different combination types, extract the corresponding strategy traits respectively, and make the host structure hold the currently effective strategy trait through a pointer; Establish an AsRef bridge relationship between the outer composite type and the inner host structure, and use BlanketImplementation to enable the outer composite type that meets the AsRef constraint to automatically obtain the corresponding external capability trait; During the object construction phase, a strategy instance is injected into the host structure, enabling the composite type of subtype semantics to implement method rewriting by replacing some strategy instances, while the unreplaced strategy instances retain the default implementation method of the host structure. When a strategy instance needs to call an implementation method on a host structure that has not yet been constructed, a shared, mutable host slot is created, and the real host structure is written into the host slot using a loop-based Arc constructor. Different specific types that have been constructed are placed into a heterogeneous polymorphic container in the form of external capability traits, and the corresponding strategy instances are invoked through dynamic dispatch of external capability traits.

2. The Rust language inheritance and method overriding method according to claim 1, characterized in that, The process of enabling the host structure to hold the currently effective policy trait via a pointer includes: The host structure holds the corresponding strategy trait in the Arc field, and the corresponding method is overridden by replacing the strategy trait.

3. The Rust language inheritance and method overriding method according to claim 2, characterized in that, The process of the host structure holding the corresponding strategy trait in the Arc field and rewriting the corresponding method by replacing the strategy trait includes: The logic that is easily rewritten is extracted as a strategy trait, and the host holds `Arc`.<dyn XXX> `, where XXX is the name of the strategy trait.

4. The Rust language inheritance and method overriding method according to claim 1, characterized in that, The external capability trait includes: The first capability trait declares the first and second methods; The second ability trait combines the first ability trait with the third ability trait, and declares the third method and the fourth method; The third capability trait declares the fifth method.

5. The Rust language inheritance and method overriding method according to claim 1, characterized in that, The process of establishing an AsRef bridge relationship between the outer composite type and the inner host structure, and automatically obtaining the corresponding external capability trait for the outer composite type that satisfies the AsRef constraint through Blanket Implementation, includes: Through generic constraints and Blanket Implementation, any outer composite type that satisfies the AsRef conversion constraint automatically obtains the default method implementation of the corresponding external capability trait; The outer composite type automatically generates a multi-layer AsRef forwarding chain through macro annotations to realize the reference conversion from the outer composite type to the inner host structure.

6. The Rust language inheritance and method overriding method according to claim 1, characterized in that, The composite type of the subtype semantics is the outer composite type. The outer composite type holds the inner host structure only through pointer references without copying the fields of the inner host structure. During the object construction phase, the outer composite type rewrites the corresponding methods by replacing some strategy instances. The strategy instances that are not replaced use the default implementation method of the inner host structure, and the strategy instances are not replaced after the object construction is completed.

7. The Rust language inheritance and method overriding method according to claim 1, characterized in that, The process of establishing a shared, variable host slot includes: A shared variable slot is generated by annotating the constructor, and the shared variable slot is passed into the constructor of the strategy instance, so that the strategy instance reserves a host reference during the registration phase. The process of using a loop to construct and write the real host structure into the host_slot includes: During the construction phase, the real host structure is written into the shared variable slot by using the new_cyclic method of the smart pointer with circular references, so that the strategy instance automatically obtains a valid host reference after construction is completed.

8. A device for inheritance and method overriding in the Rust language, characterized in that, include: The external capability definition module is used to define external capability traits and set default methods in the external capability traits. The default methods are then converted to obtain the corresponding host structure through AsRef conversion and call the implementation methods in the host structure. The strategy extraction module is used to extract the corresponding strategy traits for methods that need to be rewritten by different combination types, and to make the host structure hold the currently effective strategy trait through a pointer; The bridging module is used to establish an AsRef bridging relationship between the outer composite type and the inner host structure, and through Blanket Implementation, the outer composite type that meets the AsRef constraint automatically obtains the corresponding external capability trait. The strategy injection module is used to inject strategy instances into the host structure during the object construction phase, so that the composite type of subtype semantics can implement method rewriting by replacing some strategy instances, and the unreplaced strategy instances can use the default implementation method of the host structure. The loop constructor module is used to create a shared, variable host slot (host_slot) when a strategy instance needs to call an implementation method on a host structure that has not yet been constructed, and to use the loop Arc constructor to write the real host structure into the host_slot. The polymorphic container module is used to put different constructed specific types into the heterogeneous polymorphic container in the form of external capability traits, and to call the corresponding strategy instance through dynamic dispatch of external capability traits.

9. A computer device, comprising a memory, a processor, and a computer program stored in the memory and executable on the processor, characterized in that, When the processor executes the program, it implements the method as described in any one of claims 1-7.

10. A computer-readable storage medium having a computer program stored thereon, characterized in that, When the program is executed by the processor, it implements the method as described in any one of claims 1-7.