Skip to content

How to traverse given slice env and check if multiple variables matches the given condition #282

@Dentrax

Description

@Dentrax

I was struggling to create expressions for slices. I tried to write a bunch of expressions but couldn't able to end with a success compilation. What I want to do is:

  • Given env is an []
  • Enforce Name: E is existed in slice (any)
  • If exists, must be Active: true (skip if it does not exist)

But I couldn't able to match E against a given Name field: any(#, {Name matches 'E'}) (tried both of . and #, fails with cannot use pointer accessor outside closure). Also tried Name in ['E'] but fails: invalid operation: int(string).

Here is an example snippet:

package main

import (
	"fmt"

	"github.com/antonmedv/expr"
)

type Inputs []Input

type Input struct {
	Name   string
	Active bool
}

func main() {
	inputs := []Input{
		{Name: "A", Active: true},
		{Name: "B", Active: false},
		{Name: "C", Active: true},
		{Name: "D", Active: false},
		{Name: "E", Active: true},
		{Name: "F", Active: false},
	}

	code := `WHAT HERE TO EVAL: Name = 'E' is exist and Active = 'true'?`

	program, err := expr.Compile(code, expr.Env(inputs))
	if err != nil {
		panic(err)
	}

	output, err := expr.Run(program, inputs)
	if err != nil {
		panic(err)
	}

	fmt.Println(output)
}

Can you please help me on this? Thanks!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions