V has two kinds of reflection, one at run time and one at compile time. Run-time reflection works while the program is running. Compile-time reflection works while the program is being compiled.
In this article, we will look at run-time reflection; compile-time reflection is described in the Compile-time reflection article.
Unlike compile-time reflection, run-time reflection allows you to get type/method information at run time.
module is responsible for working with run-time reflection.
Consider a basic example of working with reflection:
reflection.type_of() function returns an object of type
reflection.Type that describes the
type of the value passed to it.
Iterate over methods of a type
reflection.Type structure contains a
sym field of type
contains additional information about the type.
methods field contains all methods of the type:
methods field is of type
which contains information about the method.
Check if a return type is Option or Result
When we iterate over methods or functions, we can get a function return type from
return_typ field of the
return_typ field is of type
This type has a
has_flags() method that allows you to get the type flags.
For example, we can check if the return type is
Check if a type is a map or array
kind field of the
reflection.TypeSymbol structure contains a kind of
So for example, to check if the type is
array, we can do the following:
See all type options in
Get all functions/structs/etc
To get a list of all functions/structs/enumerations/etc., functions of the
family are used.
For example, to get a list of all functions, we can do the following:
reflection.get_funcs()returns all functions that are defined including builtin functions.
This is a brief introduction to run-time reflection.
module documentation for more information.