Variable defined in Golang [duplicate] - go

This question already has answers here:
Assigning value in Golang
(3 answers)
Closed 7 years ago.
I create a var of type
var RespData []ResponseData
type ResponseData struct {
DataType string
Component string
ParameterName string
ParameterValue string
TableValue *[]Rows
}
type TabRow struct {
ColName string
ColValue string
ColDataType string
}
type Rows *[]TabRow
I want to fill TableValue of type *[]Rows.
Can you please tell me with an example by assigning any values in the TableValue.

Slices are reference type (it is already a kind of pointer), so you don't need a pointer to a slice (*[]Rows).
You can use a slice of slices though TableValue []Rows, with Rows being a slice of pointers to TabRow: Rows []*TabRow.
tr11 := &TabRow{ColName: "cname11", ColValue: "cv11", ColDataType: "cd11"}
tr12 := &TabRow{ColName: "cname12", ColValue: "cv12", ColDataType: "cd12"}
row1 := Rows{tr11, tr12}
rd := &ResponseData{TableValue: []Rows{row1}}
fmt.Printf("%+v", rd )
See this example.

Related

cannot use mapToPrint (variable of type map[string]CustomStruct) as type map[string]any - golang [duplicate]

This question already has an answer here:
Gomock cannot use type map[string]*mockFoo as map[string]foo
(1 answer)
Closed 4 months ago.
In my function I was receiving an argument that contained a map for which the value's type was any. I would have thought that any type could therefore be sent, but I got the following error when I tired to use map[string]CustomStruct:
cannot use mapToPrint (variable of type map[string]CustomStruct) as type map[string]any in argument to printMap.
If I create the map with type's value any, everything works, including the assignment of CustomStruct to map values.
Here is a reproducing example:
type CustomStruct struct {
name string
}
func main() {
mapToPrint := make(map[string]CustomStruct, 0)
mapToPrint["a"] = CustomStruct{"a"}
mapToPrint["b"] = CustomStruct{"b"}
printMap(mapToPrint)
}
func printMap(mapToPrint map[string]any) {
for key, value := range mapToPrint {
fmt.Println(key, value)
}
}
go.dev
As the go FAQ says here:
It is disallowed by the language specification because the two types do not have the same representation in memory.
As the FAQ suggests, simply copy the data from your map into a map with value type any, and send it like so to the function:
printableMap := make(map[string]any, len(mapToPrint))
for key, value := range mapToPrint {
printableMap[key] = value
}

Get value from a map[string]map[string]interface{} in Golang [duplicate]

This question already has answers here:
get value form nested map type map[string]interface{}
(2 answers)
Accessing Nested Map of Type map[string]interface{} in Golang
(2 answers)
How do you extract a value out of a golang map[string] string thats typed with interface{} [duplicate]
(1 answer)
Explain Type Assertions in Go
(3 answers)
how to access nested Json key values in Golang
(3 answers)
Closed last year.
I have this structure in golang:
type ScanView struct {
FileInput []ScanInput `json:"inputs"`
Report RegulaReport `json:"report"`
}
type FileInput struct {
Filepath string `json:"filepath"`
Resources map[string]map[string]interface{} `json:"resources"`
}
I need to assign values to the map depending on the key, I'm doing something like this:
for i, r := range output.Inputs {
if filepath.IsAbs(r.Filepath) {
relPath, err := filepath.Rel(inputDir, r.Filepath)
if err != nil {
return "", fmt.Errorf("some error log")
}
output.Inputs[i].Resources["_source_location"]["path"] = relPath -> here I need to assign the value for the _source_location key
output.Inputs[i].Resources["_filepath"][""] = relPath -> here I need to assign the value for the _filepath key
}
}
No pretty sure how can I achieve that for a map[string]map[string]interface{} in Golang. Thanks!

Convert []interface{} into type []string [duplicate]

This question already has answers here:
Type converting slices of interfaces
(9 answers)
Closed 2 years ago.
I have value [token code id_token] from map, value of map type []interface{}
resp := result["response_types"]
resp is type []interface{}.
i need to convert it to: clientobj.ResponseTypes
type client struct{
ResponseTypes sqlxx.StringSlicePipeDelimiter `json:"response_types" db:"response_types"`
}
in package sqlxx
package sqlxx
type StringSlicePipeDelimiter []string
is there is to convert it?
To convert a []inteface{} to []string, you just iterate over the slice and use type assertions:
// given resp is []interface{}
// using make and len of resp for capacity to allocate the memory in one go
// instead of having the runtime reallocate memory several times when calling append
str := make([]string, 0, len(resp))
for _, v := range resp {
if s, ok := v.(string); ok {
str = append(str, s)
}
}
The real question here is how you end up with a variable of type []interface{} in the first place. Is there no way for you to avoid it? Looking at the StringSlicePipeDelimiter type itself, it has the Scan method (part of the interface required to scan values from the database into the type) right here, so I can't help but wonder why you're using an intermittent variable of type []interface{}

"..." notation in append() doesn't work for appending different type slices [duplicate]

This question already has answers here:
Type converting slices of interfaces
(9 answers)
Closed 4 months ago.
I need an abstracted slice that contains multiple types. The most simplified code is this:
package main
import "fmt"
type A interface{}
type X string
func main() {
sliceA := make([]A, 0, 0)
sliceX := []X{"x1", "x2"}
var appendedSlice []A
appendedSlice = append(sliceA, sliceX[0], sliceX[1]) // (1) works
appendedSlice = append(sliceA, sliceX...) // (2) doesn't work
fmt.Println(appendedSlice)
}
In my real program, the interface A defines some functions, and X and also other types implement it.
Line (2) raises an error cannot use sliceX (type []X) as type []A in append.
I thought (2) is a syntax sugar for (1), but I'm probably missing something... Do I have to always add an element X into slice A one by one?
Thank you guys in advance!
The problem is that interface{} and string are two different types.
To convert a slice from string to interface{} you will have to do it in one of the following ways:
create sliceA and initialize its size to sliceX length
sliceA := make([]A, len(sliceX))
for ix, item := range sliceX {
sliceA[ix] = item
}
dynamically append sliceX items to appendedSlice
var appendedSlice []A
for ix := range sliceX {
appendedSlice = append(appendedSlice, sliceX[ix])
}
Please read more here
Convert []string to []interface{}

Cannot assign struct field in nested map Golang [duplicate]

This question already has answers here:
Golang: I have a map of int to struct. Why can't I directly modify a field in a map value? [duplicate]
(1 answer)
Why do I get a "cannot assign" error when setting value to a struct as a value in a map? [duplicate]
(2 answers)
Cannot assign to struct field in a map
(5 answers)
Closed 4 years ago.
I have the next structure:
type filesDB struct {
Name string
Content []byte
}
type fileDB struct {
Files map[string]filesDB
}
Well, when I try to save data in JSON format with the maps, I try this:
First, I make a map var:
var filesDatabase = map[string]fileDB{}
Then, i try to insert data:
var f filesDB
fidb := map[string]filesDB{}
f.Name= filename
f.Content= encrypt(b, sUser[user].Cipher)
fidb[filename] = f
filesDatabase[user].Files = fidb
jsonDB, err := json.Marshal(filesDatabase)
So, when I try to run the script, I get the next error:
cannot assign to struct field filesDatabase[user].Files in map
How can I resolve this error? Thanks!

Resources