'Cannot use "a" (type string) as type in array element in go
I'm pretty new to Golang and I have an issue with adding items to Array.
I use this link as a reference golang-book.
I have this struct:
package models
type FileMD struct {
fileName string
fileSize int
}
I tried to do it 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?
Solution 1:[1]
I am not sure but I think you are looking for:
fileList[0] = FileMD{"a", 1}
Or maybe:
fileList := []FileMD{{"a", 1}, {"b", 2}}
Solution 2:[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.)
1) With a literal:
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}}
2) New, initialized array/slice and filling it:
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}
Final Note
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | cnicutar |
Solution 2 |