tryfunc

package
v2.22.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 26, 2024 License: MPL-2.0 Imports: 7 Imported by: 54

README

"Try" and "can" functions

This Go package contains two cty functions intended for use in an hcl.EvalContext when evaluating HCL native syntax expressions.

The first function try attempts to evaluate each of its argument expressions in order until one produces a result without any errors.

try(non_existent_variable, 2) # returns 2

If none of the expressions succeed, the function call fails with all of the errors it encountered.

The second function can is similar except that it ignores the result of the given expression altogether and simply returns true if the expression produced a successful result or false if it produced errors.

Both of these are primarily intended for working with deep data structures which might not have a dependable shape. For example, we can use try to attempt to fetch a value from deep inside a data structure but produce a default value if any step of the traversal fails:

result = try(foo.deep[0].lots.of["traversals"], null)

The final result to try should generally be some sort of constant value that will always evaluate successfully.

Using these functions

Languages built on HCL can make try and can available to user code by exporting them in the hcl.EvalContext used for expression evaluation:

ctx := &hcl.EvalContext{
    Functions: map[string]function.Function{
        "try": tryfunc.TryFunc,
        "can": tryfunc.CanFunc,
    },
}

Documentation

Overview

Package tryfunc contains some optional functions that can be exposed in HCL-based languages to allow authors to test whether a particular expression can succeed and take dynamic action based on that result.

These functions are implemented in terms of the customdecode extension from the sibling directory "customdecode", and so they are only useful when used within an HCL EvalContext. Other systems using cty functions are unlikely to support the HCL-specific "customdecode" extension.

Index

Constants

This section is empty.

Variables

CanFunc tries to evaluate the expression given in its first argument.

TryFunc is a variadic function that tries to evaluate all of is arguments in sequence until one succeeds, in which case it returns that result, or returns an error if none of them succeed.

Functions

This section is empty.

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL