I'm pretty new to golang and I have an issue with adding items to Array.
I use this link as reference golang-book.
I have this struct:
package models
type FileMD struct {
fileName string
fileSize int
}
I tired to do it in both ways but I failed.
fileList := [...]models.FileMD{"a", 1: "b", 2}
var fileList [...]models.FileMD
fileList[0] = "a", 1
What is the correct way?
I am not sure but I think you are looking for:
fileList[0] = FileMD{"a", 1}
Or maybe:
fileList := []FileMD{{"a", 1}, {"b", 2}}
First you need to decide if you want an array or a slice.
Once you decided, you have basically 2 options:
(Try the complete application on the Go Playground.)
Initialize your array/slice with a Composite literal (either an array or slice literal) and you're done.
Arrays:
fileArr10 := [2]FileMD{FileMD{"first", 1}, FileMD{"second", 2}}
// Or short:
fileArr11 := [2]FileMD{{"first", 1}, {"second", 2}}
// With length auto-computed:
fileArr20 := [...]FileMD{FileMD{"first", 1}, FileMD{"second", 2}}
// Or short:
fileArr21 := [...]FileMD{{"first", 1}, {"second", 2}}
Slices (note the only difference between array and slice literals is that length is not specified):
fileSl10 := []FileMD{FileMD{"first", 1}, FileMD{"second", 2}}
// Or short:
fileSl11 := []FileMD{{"first", 1}, {"second", 2}}
Create a new, initialized array/slice and fill it by assiging values to its elements.
Array:
fileArr := [2]FileMD{}
fileArr[0] = FileMD{"first", 1}
fileArr[1] = FileMD{"second", 2}
Slice: (you can create slices with the built-in function make
)
fileSl := make([]FileMD, 2)
fileSl[0] = FileMD{"first", 1}
fileSl[1] = FileMD{"second", 2}
Your struct FileMD
is part of a package and it contains unexported fields (fields whose name start with lowercased letters).
Unexported fields are not accessible from outside of the package. This also means that when you create a value of such struct, you cannot specify the initial values of unexported fields.
So if you try to create a value of FileMD
from outside of package models
, you can only create zero-valued FileMD
s like this: FileMD{}
. Make your fields exported and then you can specify the initial values for the file name and size:
type FileMD struct {
FileName string
FileSize int
}
// Now FileMD{"first", 1} is valid outside of package models