XXX
XXX

Reputation: 633

Slice within a slice golang

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?

Upvotes: 0

Views: 1225

Answers (3)

Marco Valeri
Marco Valeri

Reputation: 491

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)

Upvotes: 0

JimB
JimB

Reputation: 109331

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}

Upvotes: 3

user142162
user142162

Reputation:

You're missing a set of square brackets:

SliceOfSlices := [][]string{Slice1, Slice2}

Upvotes: 3

Related Questions