expr icon indicating copy to clipboard operation
expr copied to clipboard

Operator override in case when env is passed as map[string]interface{}

Open shivam-940 opened this issue 3 years ago • 4 comments

Hi @antonmedv ,

We have a use case where we want to support decimal in expr library. I was thinking to use ConstantNode for representing decimal values and overriding operators like +, -, *..etc. When I am adding my function for add in environment (which is a map of string to interface{}), it gives me error function add for + operator does not have a correct signature. I have a requirement to pass environment as map[string]interface{}, so I wanted to know if there is any workaround for this? Please help!

Add Function Signature in environment

"add": func(a decimal.Decimal, b decimal.Decimal) (decimal.Decimal, error) {
			z := a.Add(b)
			return z, nil
		},

We are using github.com/shopspring/decimal library here.

Thanks

shivam-940 avatar Jun 30 '22 07:06 shivam-940

Check what operands are passed. Are they int? Try to use interface{} as parameter to check what kind of params are passed.

antonmedv avatar Jun 30 '22 07:06 antonmedv

add function is not getting picked up only. The program fails at compile step. Sharing go dev playground link: https://go.dev/play/p/3GNKkZ0OezT where it shows this error.

shivam-940 avatar Jun 30 '22 09:06 shivam-940

The overloading of operators does not support the return of errors at the moment. If you adopt the example from the documentation, it works fine, i.e. use "add": func(a interface{}, b interface{}) interface{} rather than "add": func(a interface{}, b interface{}) (interface{}, error).

On the other hand, I agree: somehow it should be possible to throw errors even when overloading operators. At least it's not clear to me how, in the concrete example, you could handle an invalid Decimal, overflows, etc. But that would be a feature request.

xio812 avatar Jun 30 '22 16:06 xio812

Panic will be okay in this case. All panics converted to errors.

antonmedv avatar Jun 30 '22 17:06 antonmedv