#Initialize a slice of structs

14 messages · Page 1 of 1 (latest)

slender ore
#

Hi All. How can I initialize a slice of structs?
Basically I am looping over a grouped object, I want to push some stats to a new array of objects so the eventual form is :
[
{quantity: int, product: string, tags: []string}
{quantity: int, product: string, tags: []string}
{quantity: int, product: string, tags: []string}
]

sick solar
#

Not sure what you mean.
If your struct is

type Something struct {
  Quantity int
  Product string
  Tags []string
}

You can simply do

var YourSlice = []Something{
  {Quantity: 1, Product: "pineapple pizza", Tags: []string{"Ew"}},
}
#

Or

var YourSlice = make([]Something, 5)
slender ore
#

i don't know what the cap or len will be

#

and i don't want to initialise it with any value

sick solar
#

So initialize with size 0 and append

slender ore
#

I come from a JS background so struggling a little to grasp the difference

#

Ah i can do that?

#

cool

#

ill test thanks

sick solar
slender ore
#

ive seen that, yeah i started it a few weeks ago.
But today i just thought screw it and to just try and build something

sick solar
#

👍

slender ore
#

Hey. Are you based in Europe or US ?
Im working on this little script / program and would love frequent feedback and I also have frequent questions if you have time for them 🙂