Home  >  Article  >  Backend Development  >  go-redis Eval func return value type when Lua script returns array

go-redis Eval func return value type when Lua script returns array

WBOY
WBOYforward
2024-02-09 08:51:33520browse

go-redis Eval func返回值类型,当Lua脚本返回数组时

php Editor Xigua is here to introduce to you the issue about the return value type of the Eval function in the go-redis library. When using a Lua script to execute the Eval function, sometimes the script returns an array. So in the go-redis library, what is the type of this return value? Let’s answer this question in detail below.

Question content

When a lua script returns a table array during an eval call, how do I convert it to a [] string in go?

redis cli returns batch replies in the following format.

1) val1
2) val2

go-redis eval function will return batch entries as

["val1", "val2"] 

Solution

redis returns the lua table array as a resp2 array. The go client will then map that response to a go native type. Relevant documentation for go-redis can be found here: lua and go types.

Simply put, the lua table does map to bulk reply, and the go client maps it to the interface fragment: []interface{}.

go-redis The scripts run and eval both return *cmd. You can use this type of method to retrieve go type output. result Given (interface{}, error), you can type assert whatever you want, otherwise stringslice is a Convenient getter to instantly retrieve []string.

So it looks like:

script := redis.NewScript(`
  local foo = {"val1", "val2"}
  return foo
`)

cmd := script.Run(/* parameters */)

i, err := cmd.Result() // (interface, error)
// or
ss, err := cmd.StringSlice() // ([]string, error)

If the values ​​are not actually all strings, use slice to get the []interface{} slice and then inspect the elements individually.

The above is the detailed content of go-redis Eval func return value type when Lua script returns array. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete