1

I found an answer about how to call the Scan variadic function in Golang using reflection. And don't have reputation to ask in there.

Here the main part of code:

values := make([]interface{}, count)
valuePtrs := make([]interface{}, count)

for rows.Next() { 
    for i, _ := range columns {
        valuePtrs[i] = &values[i]
    }    
    rows.Scan(valuePtrs...)
    ...
}

And I don't get why is this statement have to be looped? Why for is in for rows.Next?

for rows.Next() { 
  for i, _ := range columns { valuePtrs[i] = &values[i] }
  ..
}

Would valuePtrs be different on each iteration in golang? Or it's just mistake?

3
  • 1
    Calling make for the slice of values creates new variables, which will have different memory addresses each time this code is run. The loop is required because you can't get the memory addresses (pointers) of each item in the slice any other way. Commented Sep 8, 2017 at 17:07
  • Yes, but why it should be done several times? I think make could be executed once near define statement. Or it is way to clean values? Commented Oct 9, 2017 at 14:44
  • There isn't a problem with leaving the make calls local to the function. If you made them global (which I assume is what you are suggesting), that memory never gets released. If they only exist in the function, all that memory is released when the function exits. It just makes the most sense to declare locally over globally. Commented Oct 9, 2017 at 20:42

1 Answer 1

0

As I understand it from : https://golang.org/pkg/database/sql/#Rows.Scan

"Scan copies the columns in the current row into the values pointed at by dest. "

When you are passing it in specific fields you would use:

rows.scan(&myfield1, &myfield2)

But in your instance you are passing in an array, and the address of the array is not really what you want to send in, Rayfen is right in his comment above - consider the alternative:

rows.scan(&values)

That would be a pointer to a single object, not an array of pointers which is what you really are after, so you have to perform that loop so you can send in an array of pointers to the destination variables, not a pointer to the array.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.