英文:
Passing multiple values to expression.in() of aws-sdk-go-v2 for DynamoDB
问题
我正在尝试将一个值列表传递给aws-sdk-go-v2中的'IN'表达式,但我无法弄清楚如何以动态方式实现。
以下是当前的代码示例:
func Find(colors []string) ([]Trip, error) {
	db := database.GetClient()
	filt := expression.In(
		expression.Name("color"),
		expression.Value(colors[0]),
		expression.Value(colors[1]),
	)
	expr, err := expression.NewBuilder().WithFilter(filt).Build()
	if err != nil {
		fmt.Println(err)
	}
	params := &dynamodb.ScanInput{
		ExpressionAttributeNames:  expr.Names(),
		ExpressionAttributeValues: expr.Values(),
		FilterExpression:          expr.Filter(),
		TableName:                 aws.String("Test"),
	}
	resp, err := db.Scan(context.TODO(), params)
}
我想要使列表值动态化,而不是通过索引访问。像下面这样:
filt := expression.In(expression.Name("color"), expression.Value(colors))
我该如何实现这个目标?
英文:
I am trying to pass a list of values to the 'IN' expression in aws-sdk-go-v2 and I cannot figure out how to do it dynamically.
This is what it looks like now.
func Find(colors []string) ([]Trip, error) {
	db := database.GetClient()
	filt := expression.In(
		expression.Name("color"),
		expression.Value(colors[0]),
		expression.Value(colors[1]),
	)
	expr, err := expression.NewBuilder().WithFilter(filt).Build()
	if err != nil {
		fmt.Println(err)
	}
	params := &dynamodb.ScanInput{
		ExpressionAttributeNames:  expr.Names(),
		ExpressionAttributeValues: expr.Values(),
		FilterExpression:          expr.Filter(),
		TableName:                 aws.String("Test"),
	}
	resp, err := db.Scan(context.TODO(), params)
}
I'd like to make the list values dynamic without accessing using their index. Like below,
	filt := expression.In(expression.Name("color"),expression.Value(colors))
How can I achieve this?
答案1
得分: 1
请稍等,我会为您翻译以下内容:
参见将参数传递给...参数在语言规范中。
package main
import (
	"fmt";
	"github.com/aws/aws-sdk-go-v2/feature/dynamodb/expression"
)
func main() {
	colors := []string{"red", "blue", "green"}
	if len(colors) == 0 {
		panic("colors should not be empty")
	}
	values := make([]expression.OperandBuilder, len(colors))
	for i, c := range colors {
		values[i] = expression.Value(c)
	}
	filter := expression.In(
		expression.Name("color"),
		values[0],
		values[1:]...,
	)
	fmt.Println(filter)
}
英文:
See Passing arguments to ... parameters in the language spec.
package main
import (
	"fmt"
	"github.com/aws/aws-sdk-go-v2/feature/dynamodb/expression"
)
func main() {
	colors := []string{"red", "blue", "green"}
	if len(colors) == 0 {
		panic("colors should not be empty")
	}
	values := make([]expression.OperandBuilder, len(colors))
	for i, c := range colors {
		values[i] = expression.Value(c)
	}
	filter := expression.In(
		expression.Name("color"),
		values[0],
		values[1:]...,
	)
	fmt.Println(filter)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论