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

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!

Related

golang: passing pointer to struct to function doesn't update that struct's field in called function [duplicate]

This question already has answers here:
Change values while iterating
(4 answers)
Range references instead values
(8 answers)
increment a struct var in a range loop [duplicate]
(1 answer)
How to return changed values of slice from function? [duplicate]
(2 answers)
Why can't I change the values in a range of type structure?
(2 answers)
Closed 3 days ago.
I am new to Go. I've encountered an issue with Go pointers and don't have an explanation for the unexpected behavior.
I am using using Go 1.20 on RedHat.
Here is my test case:
package main
import (
"fmt"
)
type FileStruct struct {
readyToSend int
}
func sendFile(fileStr *FileStruct) {
fileStr.readyToSend = 2
}
func readFileFeeder(filesArr []FileStruct) {
filesArr[0].readyToSend = 1
for _, file := range filesArr {
fmt.Printf("TYPE=%T\n", &file)
sendFile(&file)
fmt.Printf("After range readyToSend=%v\n", filesArr[0].readyToSend)
}
fmt.Printf("TYPE=%T\n", &filesArr[0])
sendFile(&filesArr[0])
}
func main() {
var file1 *FileStruct = new(FileStruct)
filesArr := make([]FileStruct, 1)
filesArr[0] = *file1
fmt.Printf("Before readyToSend=%v\n", filesArr[0].readyToSend)
readFileFeeder(filesArr)
fmt.Printf("After readyToSend=%v\n", filesArr[0].readyToSend)
}
output:
==\> go run test.go
Before readyToSend=0
TYPE=\*main.FileStruct
After range readyToSend=1
TYPE=\*main.FileStruct
After readyToSend=2
How come when I call sendFile(&file) inside the for loop the value of fileStr.readyToSend doesn't get updated?
When I call sendFile(&filesArr[0]) right after the for loop the value gets updated as expected.
I would expect that fileStr.readyToSend would get updated to 2 in both cases.
How would you update this sample code to make this work?
Thanks

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
}

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!

how to assign only on return value of a function to field of an struct in golang? [duplicate]

This question already has answers here:
Multiple values in single-value context
(6 answers)
Closed 5 years ago.
let's say we have a struct like this:
type Data struct {
a int
}
and we want to get a single return value of a function that returns multiple values and assign it to an object of Data, for example
data := Data {
a: strconv.Atoi("1000")
}
the code above does not work because Atoi returns two value, a number and an error, so we need to handle the extra value (error) somehow, but in my case, I do not need to evaluate error value and it is not possible to dismiss it using _ keyword.
how can I achieve this when initializing a struct, I want to get rid of the error return value
There is no generic way to get just one of returned parameters (Maybe you could implement something with reflect package that returns interface{}).
Other than that it's not good to ignore errors. If you are sure that there's no error implement a helper function like this:
func myAtoi(s string) int {
i, err := strconv.Atoi(s)
if err != nil {
panic(err)
}
return i
}
data := Data {
a: myAtoi("1000")
}

Variable defined in Golang [duplicate]

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.

Resources