Printing map into file


(Mantas Silanskas) #1

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


(Mantas Silanskas) #2

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


(Holloway) #3

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.


(Mantas Silanskas) #4

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


(Holloway) #5

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


(Mantas Silanskas) #6

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?


(Holloway) #7

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

(Mantas Silanskas) #8

Thank you sir !


(Holloway) #9

Welcome. :slight_smile: