Printing map into file

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 :
image

2 Likes

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)
}

2 Likes

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.

1 Like

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

1 Like

No. no query is needed. The for loop with dump the key-value pair into separate variables.

1 Like

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?

1 Like

That’s for single query. :rofl: 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()
}
...
2 Likes

Thank you sir !

1 Like

Welcome. :slight_smile:

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.