Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang create a slice of maps

I was trying to create a slice of maps the following way.

keyvalue := make(map[string]interface{})
keyvalueslice := make([]keyvalue, 1, 1)

I was trying to create it just like the way string slice is created, however I am getting an error saying keyvalue is not a type. I am creating this slice to append data to keyvalueslice variable later.

Can someone explain what is wrong?

like image 320
scott Avatar asked Feb 12 '16 12:02

scott


People also ask

How do you make a slice in Golang?

In Go language, a slice can be created and initialized using the following ways: Using slice literal: You can create a slice using the slice literal. The creation of slice literal is just like an array literal, but with one difference you are not allowed to specify the size of the slice in the square braces[].

Can a slice Be map key Golang?

No, sorry, slices cannot be used as map keys.

What is difference between array and slice in Golang?

Slices in Go and Golang The basic difference between a slice and an array is that a slice is a reference to a contiguous segment of an array. Unlike an array, which is a value-type, slice is a reference type. A slice can be a complete array or a part of an array, indicated by the start and end index.

What is Golang slice?

Slices are similar to arrays, but are more powerful and flexible. Like arrays, slices are also used to store multiple values of the same type in a single variable. However, unlike arrays, the length of a slice can grow and shrink as you see fit.


1 Answers

keyvalue is a variable not a type, you can't create a slice of variables. If you want to define custom type you can do this like

type keyvalue map[string]interface{}

then you can create a slice of keyvalues:

keyvalueslice := make([]keyvalue, 1, 1)

Example on playground

Or you can do this without defining custom type:

keyvalueslice := make([]map[string]interface{}, 1, 1)
like image 68
wlredeye Avatar answered Oct 17 '22 17:10

wlredeye