-1

I have a string in Go ('["a","b","50"]') which I need to convert into a []string type. To me, that is basically evaluating the string, but I have no idea how to do this in Go (I come from Python). I did search the strconv package documentation, but did not really find anything that worked.

2
  • Note that eval is a very dangerous thing in general. The Python version has been revised a lot over time and in Python3 you can restrict it to reduce this danger, but if you don't carefully vet input and just blindly feed it to some execution engine, you get xkcd.com/327 😀 If your string is JSON, as it seems to be, see Alexey Soshin's answer. Commented Jan 1, 2020 at 22:51
  • golang is compiled, so an "eval" doesn't really exist. The string can be marshalled/encoded, and thus unmarshalled/decoded Commented Jan 1, 2020 at 23:11

1 Answer 1

2

You could use json package for that, as your string is clearly a JSON array:

import (
    "encoding/json"
    "fmt"
)

func main() {
    str := `["a","b","50"]`
    slice := []string{}
    err := json.Unmarshal([]byte(str), &slice)

    if err == nil {
        fmt.Printf("%v\n", slice)
    }
}

An alternative would be to use strings.Split(str, ","), but then you'll have to strip those [] and ""

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.