Skip to content
This repository was archived by the owner on May 24, 2023. It is now read-only.

Commit 56d6796

Browse files
committed
Document type-conversions in Scan(); fix #38
1 parent 5be9c38 commit 56d6796

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed

retrieving.md

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,27 @@ Second, you should always check for an error at the end of the `for rows.Next()`
7979
loop. If there's an error during the loop, you need to know about it. Don't just
8080
assume that the loop iterates until you've processed all the rows.
8181

82+
How Scan() Works
83+
================
84+
85+
When you iterate over rows and scan them into destination variables, Go performs data
86+
type conversions work for you, behind the scenes. It is based on the type of the
87+
destination variable. Being aware of this can clean up your code and help avoid
88+
repetitive work.
89+
90+
For example, suppose you select some rows from a table that is defined with
91+
string columns, such as `VARCHAR(45)` or similar. You happen to know, however,
92+
that the table always contains numbers. If you pass a pointer to a string, Go
93+
will copy the bytes into the string. Now you can use `strconv.ParseInt()` or
94+
similar to convert the value to a number. You'll have to check for errors in the
95+
SQL operations, as well as errors parsing the integer. This is messy and
96+
tedious.
97+
98+
Or, you can just pass `Scan()` a pointer to an integer. Go will detect that and
99+
call `strconv.ParseInt()` for you. If there's an error in conversion, the call
100+
to `Scan()` will return it. Your code is neater and smaller now. This is the
101+
recommended way to use `database/sql`.
102+
82103
Preparing Queries
83104
=================
84105

0 commit comments

Comments
 (0)