英文:
Golang sql driver, why do we need to pass a slice of a byte array as an arguement to the query
问题
我正在验证来自mariadb数据库的哈希值,并且我不确定为什么我必须对数组进行切片,而不是直接传递数组。
我在golang中对令牌进行哈希处理,像这样:
// 这个类型是[32]uint8
tokenHash := sha256.Sum256(([]byte(token)))
然后我尝试将令牌哈希与数据库中保存的哈希进行匹配,代码如下:
// tokenHash[:] 的类型是 []uint8
err := m.DB.QueryRowContext(ctx, query, tokenHash[:], time.Now())
如果我不进行切片操作,我会得到以下错误:sql: converting argument $1 type: unsupported type [32]uint8, a array
我已经让它工作了,但我只是不明白为什么它能工作。
如果你感兴趣的话,这是SQL语句:
query := `SELECT u.id, u.first_name, u.last_name, u.email
FROM
users u
INNER JOIN tokens t on (u.id = t.user_id)
WHERE t.token_hash = ?
and t.expiry > ?
`
我在这里检查了类型:
https://play.golang.org/p/5xUAgv_sdfA
英文:
I am validating a hash from a mariadb database, and I'm unsure of why I have to take a slice of an array, instead of passing just the array.
I am hashing the token in golang like this:
// This type is a [32]uint8
tokenHash := sha256.Sum256(([]byte(token)))
Then I'm trying to match the token hash to the hash saved in the database here
// tokenHash[:] is of type []uint8
err := m.DB.QueryRowContext(ctx, query, tokenHash[:], time.Now())
The error I get if I don't take a slice is: sql: converting argument $1 type: unsupported type [32]uint8, a array
I have it working, but I just don't understand why it's working.
The sql if interesed is
query := `SELECT u.id, u.first_name, u.last_name, u.email
FROM
users u
INNER JOIN tokens t on (u.id = t.user_id)
WHERE t.token_hash = ?
and t.expiry > ?
`
I checked the types here:
https://play.golang.org/p/5xUAgv_sdfA
答案1
得分: 2
一个数组不是一个切片。一个数组[n]Type是一个数据类型,它有n
个Type
类型的项,与[m]Type
不同,如果m!=n
。也就是说,如果有一个函数:
f(args [8]byte)
你不能将[9]byte
传递给它。它们是两种不同的类型。
数组是按值传递的。例如,当你调用f(arr)
时,arr
的所有元素都会被传递给f
,而不是arr
的引用。
切片是对数组的一种视图。它可以根据需要增长。当你将一个切片传递给一个函数时,你传递的是一个三元组(长度、容量、指向数组的指针)。
这就是为什么当你将一个数组传递给一个需要切片的函数时,你必须先从该数组创建一个切片的原因。
英文:
An array is not a slice. An array [n]Type is a data type that has n
items of Type
, which is different from [m]Type
, if m!=n
. That is, if there is a function:
f(args [8]byte)
you cannot pass [9]byte
to it. Those are two different types.
Arrays are passed by value. For instance, when you call f(arr)
, all elements of arr
are passed to f
, not a reference to the arr
.
A slice is a view over an array. It can grow as necessary. When you pass a slice to a function, you pass a triple (len,cap,pointer to array).
That's the reason why when you pass an array to a function that needs a slice, you have to create a slice from that array first.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论