0

I'm trying to split a comma separated string and use the values to initalize a struct. This is how I do it right now:

type Address struct {
    Street  string
    City    string
    ZipCode string
}
    
s := strings.Split("street,city,zip", ",")
data := Address{Street: s[0], City: s[1], ZipCode: s[2]}

The problem I'm having is that I have to handle this input as well:

"street,"
"street,city"

Any idea how to do it without going out of range? I've looked into unpacking with triple dots syntax ... but structs does not seem to support it.

3
  • 1
    Check len(s) to ensure you don't index out of bounds. Commented Apr 5, 2021 at 20:50
  • @colm.anseo If I have multiple structs and multiple optional fields, its gonna be a lot of checks. Is that normal in Go, no other way around? Commented Apr 5, 2021 at 20:54
  • It is normal to check the length of a slice when the length is not known at compile time. Commented Apr 5, 2021 at 21:06

2 Answers 2

3

Check the length of the slice before accessing the element:

data := Address{}
s := strings.Split("street,city,zip", ",")
data.Street = s[0]
if len(s) > 1 {
    data.City = s[1]
}
if len(s) > 2 {
    data.ZipCode = s[2]
}

If this comes up a lot, then write a simple helper function:

func get(s []string, i int) string {
    if i >= len(s) {
        return ""
    }
    return s[i]
}

Use it like this:

data := Address{Street: get(s, 0), City: get(s, 1), ZipCode: get(s, 2)}
Sign up to request clarification or add additional context in comments.

Comments

1

If you'd rather use slightly more memory and less checks, you could also do:

s := strings.Split("street,city,zip", ",")
s = append(s, make([]string, 3 - len(s))...) // Change 3 to however many fields you expect
data := Address{Street: s[0], City: s[1], ZipCode: s[2]}

What this does is append empty strings to the slice to ensure it always has the right number of elements. Playground example: https://play.golang.org/p/Igj6yT5fffl

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.