I know that for string array []string
I can use strings.Join(a []string, ',')
but I want to do the same thing for an integer array []int
.
My usecase is something like this for a query where variants
is []map[string]int
var Ids []int
sqlStr := "select id from mapping where my_id in ("
for _, mp := range variants {
sqlStr += "?,"
Ids = append(Ids, mp["id"])
}
sqlStr = strings.TrimRight(sqlStr, ",")
rows, err := db.Query(sqlStr+")", strings.Join(Ids, ',')) // I can't do this because Join needs String array
How to achieve this?
Here is an efficient way to do that:
func sqlIntSeq(ns []int) string {
if len(ns) == 0 {
return ""
}
// Appr. 3 chars per num plus the comma.
estimate := len(ns) * 4
b := make([]byte, 0, estimate)
// Or simply
// b := []byte{}
for _, n := range ns {
b = strconv.AppendInt(b, int64(n), 10)
b = append(b, ',')
}
b = b[:len(b)-1]
return string(b)
}
You can use it in the SQL queries like that:
query := `SELECT * FROM table WHERE id IN (` + sqlIntSeq(ids) + `)`
Playground: https://play.golang.org/p/zi7YYetGu7.
Make IDs
a []string
and convert the integers when you append them
var IDs []string
for _, i := range []int{1, 2, 3, 4} {
IDs = append(IDs, strconv.Itoa(i))
}
fmt.Println(strings.Join(IDs, ", "))
I would prefer to use json.Marshal
. It is much simple and easy to use.
data := []int{100, 200, 300}
s, _ := json.Marshal(data)
fmt.Println(strings.Trim(string(s), "[]"))
I hope this helps you. Please feel free to ask in case of doubts. WebsiteLink