Hello guys I wanted to ask if is possible to print map members data to file?
I tried doing :
nf , err := os.Create(“results.txt”)
if err != nil {
log.Fatal("Error: ", err)
}
io.Copy(nf, reisai.ReisaiDataRow{})
but I get error :
Hello guys I wanted to ask if is possible to print map members data to file?
I tried doing :
nf , err := os.Create(“results.txt”)
if err != nil {
log.Fatal("Error: ", err)
}
io.Copy(nf, reisai.ReisaiDataRow{})
but I get error :
for _, result := range results{
io.Copy(nf, result)
}
tried adding to for cycle and than get them to file as I get detailed map info with similar cycle while just printing to my terminal :
for _, reisai := range reisai1 {
fmt.Println(reisai)
}
You need to do the key:value encoding on your own side before writing it into the file, as in:
// pseudocodes
nf , err := os.Create("results.txt")
if err != nil {
// handle error
}
...
key := "label"
value := myMap[key]
_, err := fmt.Fprintf(ns, "%v is %v\n", key, value) // format the output before write to file.
if err != nil {
// handle error
}
...
Loop over map objects is:
for key, value := range myMap {
...
}
Keep in mind that they are never in order like an array.
Do I need key value as if I want print all entries in map? I mean all 50+ lines of it? They dont have identical value they all are different
No. no query is needed. The for loop with dump the key-value pair into separate variables.
I’m sorry I am pretty new to go.
I tried code like :
nf , err := os.Create(“results.txt”)
if err != nil {
log.Fatal("Error: ", err)
}
key := “”
value := results[key]
fmt.Fprintf(nf, “%v is %v\n”, key, value)
if err != nil {
log.Fatal("Error: ", err)
}
all I get in file is : is .
So in my mind my printing doen’t get map values at all?
That’s for single query. To dump the entire map, you need to use the for
loop version.
Code should look something like this:
// pseudocodes
nf , err := os.Create("results.txt")
if err != nil {
// handle error
}
defer func() {
err := nf.Close()
if err != nil {
// handle unable to close file.
}
}()
...
for key, value := range myMap {
_, err := fmt.Fprintf(nf, "%v is %v\n", key, value)
if err != nil {
// handle error
}
nf.Sync()
}
...
Thank you sir !
Welcome.
This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.