Skip to content

[QUESTION] Using Expr.Function with function type arguments #858

@talvez-euovictor

Description

@talvez-euovictor

Hi @antonmedv!

I'm trying to port some of the functions provided by the lo package to have more capabilities of collection types manipulation. But I'm having a hard time trying to represent the function argument as an expression. It compiles but throws a runtime error.

Expr version: v1.17.5
Go version: go1.24.9 linux/amd64

Example of the Expr function:

import (
	"github.com/expr-lang/expr"
	"github.com/samber/lo"
)

const sliceToMapFuncParamsLen = 2

func sliceToMapFunc() expr.Option {
	return expr.Function(
		"SliceToMap",
		func(params ...any) (any, error) {
			if len(params) != 2 {
				return nil, invalidParametersNumberError("SliceToMap", sliceToMapFuncParamsLen, len(params))
			}

			slice, ok := params[0].([]any)
			if !ok {
				return nil, invalidParameterTypeError("SliceToMap", 0, "[]any", TypeOf(params[0]))
			}

			fn, ok := params[1].(func(any) (string, any))
			if !ok {
				return nil, invalidParameterTypeError("SliceToMap", 1, "func(any) (string, any)", TypeOf(params[1]))
			}

			return lo.SliceToMap(slice, fn), nil
		},
		new(func([]any, func(any) (string, any)) (any, error)),
	)
}

Expression examples:

SliceToMap(.data, {{string(#.key):#.value}})
SliceToMap(.data, {#.key,#.value})

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions