CodeL
CodeL

Reputation: 191

Convert string to array of integers in golang

I am looking for an answer in internet but it no one that fit my needs.

I have a string in the following format:

"[2,15,23]"

and i am trying to convert it in this format:

[2,15,23]

I need the type after the convertion to change to []int. I need to convert it because i want to use it later to make an interface type to use it in a sql query as param.

Is there any way to convert it?

Thanks

Upvotes: 3

Views: 13879

Answers (3)

hbejgel
hbejgel

Reputation: 4837

A better way using json.Unmarshal:

func main() {
    str := "[2,15,23]"
    var ints []int
    err := json.Unmarshal([]byte(str), &ints)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("%v", ints)
}

Upvotes: 7

RayfenWindspear
RayfenWindspear

Reputation: 6274

Here is a working example if you haven't figured it out based on the comments suggesting that you use json.Unmarshal

Playground link

package main

import (
    "fmt"
    "log"
    "encoding/json"
)

func main() {
    str := "[2,15,23]"
    ints, err := convertToIntSlice(str)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("%v", ints)
}

type IntSlice struct {
    Ints []int
}

func convertToIntSlice(s string) ([]int, error) {
    a := &IntSlice{}
    err := json.Unmarshal([]byte(`{"Ints":`+s+"}"), a)
    return a.Ints, err
}

Upvotes: 1

Alex Smith
Alex Smith

Reputation: 364

This is slightly hackish but you could treat it like a csv:

import (
    "encoding/csv"
    "strings"
)

in := `"[2,15,23]"`
r := csv.NewReader(strings.NewReader(in))

records, err := r.ReadAll()

Upvotes: 1

Related Questions