2

I am trying to use maps and slice of those maps to store rows returned from a database query. But what I get in every iteration of the rows.Next() and in final is the slice of the one same row from the query. It seems the problem is related to the memory place being same I store the cols, yet I could not resolve it until now.

What is the thing am I missing here:

The source code is as follows:

package main

import (
    "database/sql"
    _ "github.com/lib/pq"

    "fmt"
    "log"

    "reflect"
)
var myMap = make(map[string]interface{})
var mySlice = make([]map[string]interface{}, 0)

func main(){
    fmt.Println("this is my go playground.")

    // DB Connection-
    db, err := sql.Open("postgres", "user=postgres dbname=proj2-dbcruddb-dev password=12345 sslmode=disable")
    if err != nil {
        log.Fatalln(err)
    }
    rows, err := db.Query("SELECT id, username, password FROM userstable")
    defer rows.Close()
    if err != nil {
        log.Fatal(err)
    }

    colNames, err := rows.Columns()
    if err != nil {
        log.Fatal(err)
    }
    cols := make([]interface{}, len(colNames))
    colPtrs := make([]interface{}, len(colNames))
    for i := 0; i < len(colNames); i++ {
        colPtrs[i] = &cols[i]
    }

    for rows.Next() {
        err = rows.Scan(colPtrs...)
        if err != nil {
            log.Fatal(err)
        }
        fmt.Println("cols: ", cols)

        for i, col := range cols {
            myMap[colNames[i]] = col
        }
        mySlice = append(mySlice, myMap)

        // Do something with the map
        for key, val := range myMap {
            fmt.Println("Key:", key, "Value:", val, "Value Type:", reflect.TypeOf(val))
        }
        fmt.Println("myMap: ", myMap)
        fmt.Println("mySlice: ", mySlice)

    }
    fmt.Println(mySlice)
}

1 Answer 1

1

This is because what you are storing in the slice is a pointer to a map rather than a copy of the map.

From Go maps in action:

Map types are reference types, like pointers or slices...

Since you create the map outside the loop that updates it, you keep overwriting the data in the map with new data and are appending a pointer to the same map to the slice each time. Thus you get multiple copies of the same thing in your slice (being the last record read from your table).

To handle, move var myMap = make(map[string]interface{}) into the for rows.Next() loop so a new map is create on each iteration and then appended to the slice.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.