expr icon indicating copy to clipboard operation
expr copied to clipboard

How to compare type like `type Status string`?

Open vip-king opened this issue 4 years ago • 1 comments

In a nutshell, compare between string and type Other string will cause error like interface conversion: interface {} is main.Status, not string. Any elegant way to result this issue?

Type define:

type Status string

const (
	Success Status = "Success"
	Failure Status = "Failure"
)

func (s Status) String() string {
	if s == Success {
		return "✅"
	} else if s == Failure {
		return "❎"
	} else {
		return "👃🏻"
	}
}

Main code:

env := map[string]interface{}{
    "okay": Success,
    "fail": Failure,
    "str":  func(v interface{}) string { return fmt.Sprint(v) },
}
queries := []string{
    `true`,
    `false`,
    `str(okay)`,
    `str(okay) == "Success"`,
    `okay`,
    `okay == "Success"`,
    `str(okay) == "✅"`,
}
for _, query := range queries {
    prog, err := expr.Compile(query, expr.Env(env))
    if err != nil {
        log.Warnw("failed to compile query", "query", query, zap.Error(err))
        continue
    }

    var output interface{}
    if output, err = expr.Run(prog, env); err != nil {
        log.Warnw("failed to execute query", "query", query, zap.Error(err))
        continue
    } else {
        log.Infow("run successfully", "output", output)
    }
}

Result:

2021-08-27T18:25:04.805+0800	INFO	runexpr/main.go:57	run successfully	{"pid": 77239, "query": "true", "output": true}
2021-08-27T18:25:04.805+0800	INFO	runexpr/main.go:57	run successfully	{"pid": 77239, "query": "false", "output": false}
2021-08-27T18:25:04.806+0800	INFO	runexpr/main.go:57	run successfully	{"pid": 77239, "query": "str(okay)", "output": "✅"}
2021-08-27T18:25:04.806+0800	INFO	runexpr/main.go:57	run successfully	{"pid": 77239, "query": "str(okay) == \"Success\"", "output": false}
2021-08-27T18:25:04.806+0800	INFO	runexpr/main.go:57	run successfully	{"pid": 77239, "query": "okay", "output": "✅"}
2021-08-27T18:25:04.806+0800	WARN	runexpr/main.go:54	failed to execute query	{"pid": 77239, "query": "okay == \"Success\"", "error": "interface conversion: interface {} is main.Status, not string (1:6)\n | okay == \"Success\"\n | .....^"}
2021-08-27T18:25:04.806+0800	INFO	runexpr/main.go:57	run successfully	{"pid": 77239, "query": "str(okay) == \"✅\"", "output": true}

vip-king avatar Aug 27 '21 10:08 vip-king

Yes, operator override.

antonmedv avatar Aug 27 '21 10:08 antonmedv