0

In Go is it possible to populate a struct slice? My data is an array of strings.

a := [string1, string2, string3, string4]

type User struct {
     NickName string
}

var u []User

How do I populate u with the contents of a?

1 Answer 1

2

Use make to create the slice and a for loop to populate the slice:

u := make([]User, len(a))
for i := range a {
    u[i].NickName = a[i]
}

playground example

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

1 Comment

Thank you sir, it would have taken me a whole day to figure that out.

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.