2

Confused as to why the below is happening. TLDR; I'm passing a pointer and a "&val" to database/sql 's Scan method, and getting different results

rows, err := db.Query(selectRowsQuery)
val = new(int)

for rows.Next() {
  err = rows.Scan(val)
...
fmt.Println(val)      // 0xc0000b6c48

Val's value is a pointer. Why does val stay as a pointer?

but if I do this:

var val int
...
err = rows.Scan(&val)
fmt.Println(val)          // 0

val returns as the value. Aren't "&val" (val is an int value) and "val" (val is a pointer to int) the same thing?

2
  • 1
    To print the integer instead of the pointer in the first snippet of code, dereference the pointer: fmt.Println(*val) Commented Aug 24, 2020 at 4:50
  • Please take the Tour of Go for language fundamentals or consult any C reference on what pointers are and how they behave. Commented Aug 24, 2020 at 5:37

1 Answer 1

2

In the first case, when you do val = new(int) you are getting a pointer, and rows.Scan(val) is putting a value into the location that pointer is pointing to correctly, but you're printing fmt.Println(val): which just means you want Go to print the pointer. Which it did... the string representation of a pointer is the address it's pointing to. What you'd want to do is fmt.Println(*val), which says 'print the value that the pointer is pointing to'.

The second example works correctly because var val int initializes a value, and fmt.Println(val) prints it correctly. err = rows.Scan(&val) required you to send the address of val by calling &val because that's how we tell rows.Scan where to put the data instead of passing it data that it can't do anything with.

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

1 Comment

Thanks!! Very clear explanation, makes sense now :)

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.