Replace with "?" all elements in a slice / create a string with ?, for as many elements in a slice

huangapple go评论97阅读模式
英文:

Replace with "?" all elements in a slice / create a string with ?, for as many elements in a slice

问题

我正在做我的第一个 Golang 作业,所以这可能是一个愚蠢的问题。

我遇到了这样的情况:我需要动态创建一个查询,该查询接受一个参数的数组(切片),因此在执行前需要有相同数量的“?”。

代码如下:

var reportIds []int // 例如 [1, 2, 3, 4]

values := make([]interface{}, 0, len(reportIds))
for key, _ := range reportIds {
  values = append(values, reportIds[key])
}

statement, _ :=
    database.Prepare("DELETE FROM reports WHERE id IN ({??my_dynamic_question_marks??})")
statement.Exec(values...)

这段代码可以处理参数的值,但我不知道是否有一种简洁的方法来用“?”替换切片中的 n 个元素,以便我可以将其连接成一个字符串。
我提出了这个想法,因为它看起来很简洁,但是只要能够为切片中的每个元素创建一个带有“?, ”的字符串(最后一个元素不带逗号),任何方法都可以。

当然,我可以在 for 循环中实现一个计数器,并动态构建字符串,但我想知道是否有一种更简洁或更“官方”的方法来做到这一点。

英文:

I'm doing my first assignment in Golang, hence this may be silly question.

I have a situation where I need to create a query dynamically that takes an array (slice) of parameters, thus an equal number of "?" pre execution.

Here it is:

var reportIds []int // eg [1, 2, 3, 4]

values := make([]interface{}, 0, len(reportIds))
for  key, _ := range reportIds {
  values = append(values, reportIds[key])
}

statement, _ :=
    database.Prepare("DELETE FROM reports WHERE id IN ({??my_dynamic_question_marks??})")
statement.Exec(values...)

It works for the values but I cannot understand whether there is a clean way of replacing a n number of elements in a slice with "?" so that I could then join it into a string.
I came up with this idea since it seems clean but any way of creating a string with "?, " for as many elements in the slice would work (natually the last one without comma).

I could do that implementing a counter in the for loop of course and build the string dynamically but I was wondering whether there a cleaner or more "official" way of doing it

答案1

得分: 2

你可以构建一个由"?"字符串组成的切片,然后使用strings.Join将它们连接在一起,strings.Join接受一个字符串切片和一个分隔符:

var reportIds []int // 例如 [1, 2, 3, 4]

values := make([]interface{}, len(reportIds))
placeHolders := make([]string, len(reportIds))

for idx, reportID := range reportIds {
  values[idx] = reportID
  placeHolders[idx] = "?"
}

strings.Join(placeHolders, ",") // => "?,?,?,?"
英文:

You can build a slice of "?" strings, and then join them together with strings.Join, which accepts a slice of strings and a delimiter:

var reportIds []int // eg [1, 2, 3, 4]

values := make([]interface{}, len(reportIds))
placeHolders := make([]string, len(reportIds))

for idx, reportID := range reportIds {
  values[idx] = reportID
  placeHolders[idx] = "?"
}

strings.Join(placeHolders, ",") // => "?,?,?,?"

huangapple
  • 本文由 发表于 2021年9月9日 00:36:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/69106795.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定