reflect
trait object
Rust provides dynamic dispatch through a feature called trait objects
. Trait objects, like &Foo or Box
any
This module (std::any) contains the Any
trait, which enables dynamic typing of any 'static
type through runtime reflection. It also contains the Provider
trait and accompanying API, which enable trait objects to provide data based on typed requests, an alternate form of runtime reflection.
Any itself can be used to get a TypeId
1 | use std::fmt::Debug; |
porpular crates using Any
- oso
The Oso Library is a batteries-included framework for building authorization in your application - bevy
A refreshingly simple data-driven game engine built in Rust
macro
rust compile process
front end: rustc
- lexical analysis: Code Text -> TokenStream
- syntax analysis: TokenStream -> AST (abstract syntax tree)
- semantic analyzer:
AST -> HIR (High-Level Intermediate Representation) -> Type HIR (static type analysis, syntactic desugar, e.gfor
changed toloop
) -> MIR: (Mid-Level Intermediate Representation, scope, reference & borrow check)
back end: LLVM
LLVM IR -> machine code
macros in compiling
- declarative macros: TokenStream - expand -> TokenStream
- procedule macros: self defined AST with the help or third party crate such as syn, quote
declarative macro: macro_rules!
Declarative macros allow us to write match-like code. The match expression is a control structure that receives an expression and then matches the result of the expression with multiple patterns. Once a pattern is matched, the code associated with the pattern will be executed
1 |
|
example 1, simplified vec!
below example use macro_rules to implement a simplified version of vec!
1 |
|
example 2, unless
1 | macro_rules! unless { |
example 3, HashMap
1 | macro_rules! hashmap { |
metavariables
- item: an Item
- stmt: a Statement without the trailing semicolon (except for item statements that require semicolons)
- expr: an Expression
- ty: a Type
- ident: an IDENTIFIER_OR_KEYWORD or RAW_IDENTIFIER
- path: a TypePath style path
- tt: a TokenTree (a single token or tokens in matching delimiters (), [], or {})
- meta: an Attr, the contents of an attribute
- lifetime: a LIFETIME_TOKEN
- vis: a possibly empty Visibility qualifier
- literal: matches LiteralExpression
details to be found here