pub struct FuncDef { /* private fields */ }
Expand description
The definition of a function that can be called in HCL expressions.
It defines the function to call, and number and types of parameters that the function accepts. The parameter information is used to validate function arguments prior to calling it.
The signature of a function is defined by the Func
type alias. For available parameter
types see the documentation of ParamType
.
§Function call evaluation
When a FuncCall
is evaluated (via its
evaluate
method), the arguments are validated against the
defined function parameters before calling the function. The evaluation will stop with an error
if too few or too many arguments are provided, of if their types do not match the expected
parameter types.
Because all arguments are validated before calling the function, unnecessary length and type checks on the function arguments can be avoided in the function body.
§Examples
use hcl::eval::{Context, FuncArgs, FuncDef, ParamType};
use hcl::Value;
fn add(args: FuncArgs) -> Result<Value, String> {
let a = args[0].as_number().unwrap();
let b = args[1].as_number().unwrap();
Ok(Value::Number(*a + *b))
}
let params = [ParamType::Number, ParamType::Number];
let func_def = FuncDef::new(add, params);
let mut ctx = Context::new();
// Declare the function in the context to make it available
// during expression evaluation.
ctx.declare_func("add", func_def);
// Use the context to evaluate an expression.
// ...
Alternatively, the FuncDefBuilder
can be used to construct the FuncDef
:
let func_def = FuncDef::builder()
.param(ParamType::Number)
.param(ParamType::Number)
.build(add);
See the documentation of the FuncDefBuilder
for all available methods.
Implementations§
Source§impl FuncDef
impl FuncDef
Sourcepub fn new<P>(func: Func, params: P) -> FuncDefwhere
P: IntoIterator<Item = ParamType>,
pub fn new<P>(func: Func, params: P) -> FuncDefwhere
P: IntoIterator<Item = ParamType>,
Creates a new FuncDef
from a function and its parameters.
Note: if you want to define a FuncDef
with a variadic parameter, use the
.builder()
method. It provides a FuncDefBuilder
which also lets you define
variadic parameters.
See the type-level documentation of FuncDef
for usage examples.
Sourcepub fn builder() -> FuncDefBuilder
pub fn builder() -> FuncDefBuilder
Creates a FuncDefBuilder
.
See the type-level documentation of FuncDef
for usage examples.