0

I am trying to make a slice within a slice in golang, but have been unsuccessful. Here is my code snippet:

Slice1 := []string{"a","b","c"}
Slice2 := []string{"x","y","z"}
SliceOfSlices := []string{Slice1,Slice2}

http://play.golang.org/p/-ECPRTS0_X

Gives me the error : cannot use Slice1 (type []string) as type string in array or slice literal

How do I do this correctly?

3 Answers 3

3

You're missing a set of square brackets:

SliceOfSlices := [][]string{Slice1, Slice2}
Sign up to request clarification or add additional context in comments.

Comments

3

Slice1 and Slice2 are of type []string, so a slice of those will be a [][]string

http://play.golang.org/p/FPS5r5qbfO

Slice1 := []string{"a", "b", "c"}
Slice2 := []string{"x", "y", "z"}
SliceOfSlices := [][]string{Slice1, Slice2}

Comments

0

As suggested above, you have to add a square brackets like the following example:

Slice1 := []string{"a", "b", "c"}
Slice2 := []string{"x", "y", "z"}
SliceOfSlices := [][]string{Slice1, Slice2}

If you do not know the length of SliceOfSlices, you can also use the following approach:

SliceOfSlices := make([][]string, 0)
Slice1 := []string{"a", "b", "c"}
Slice2 := []string{"x", "y", "z"}
Slice3 := []string{"w", "w", "w"}
SliceOfSlices = append(SliceOfSlices, Slice1, Slice2, Slice3)

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.