gpt4 book ai didi

go - 为什么 `votes`的值在db.Prepare之后变了?

转载 作者:数据小太阳 更新时间:2023-10-29 03:29:27 24 4
gpt4 key购买 nike

我正在使用 http://github.com/Go-SQL-Driver/MySQL

我想从数据库中获取一个值 votes,例如“0000”,并将其更新为“1000”。在 db.Prepare() 之前它工作正常。但在此之后,votes 的值发生了变化。除了 db.Prepare() 之外,我没有对它做任何事情。我的代码是

func Vote(_type, did int, username string) (isSucceed bool) {
db := lib.OpenDb()
defer db.Close()

stmt, err := db.Prepare(
`SELECT votes
FROM users
WHERE username = ?`)
lib.CheckErr(err)

res := stmt.QueryRow(username)
stmt.Close()

var votes Votes
res.Scan(&votes)
fmt.Println(votes)//output: [48 48 48 48]
fmt.Println(string(votes))//output: 0000

isSucceed = votes.add(VoteType(_type), 1)
fmt.Println(votes)//output: [49 48 48 48]
fmt.Println(string(votes))//output: 1000

//v := []byte{[]byte(votes)[0], []byte(votes)[1], []byte(votes)[2], []byte(votes)[3]}

if isSucceed {
//Update user votes
stmt, err := db.Prepare(
`UPDATE users
SET votes = ?
WHERE username = ?`)
lib.CheckErr(err)

fmt.Println(votes)//output: [4 254 0 0]
fmt.Println(string(votes))//output: [EOT]□[NUL][NUL]
//_, _ = stmt.Exec(v, username)
_, _ = stmt.Exec(votes, username)
stmt.Close()

//Insert the vote data
stmt, err = db.Prepare(
`INSERT votes
SET did = ?, username = ?, date = ?`)
lib.CheckErr(err)

today := time.Now()
_, _ = stmt.Exec(did, username, today)
stmt.Close()
}

return
}

Votes 类型是:

type Votes []byte
type VoteType int

func (this *Votes) add(_type VoteType, num int) (isSucceed bool) {
if []byte(*this)[_type] > VOTE_MAX-1 { //beyond
isSucceed = false
} else {
[]byte(*this)[_type]++
isSucceed = true
}
return
}

最后,我将 votes 中的值复制到 v 中,效果很好。我不明白为什么更改了 votes 的值。我的代码有什么问题吗?任何帮助,将不胜感激。

最佳答案

我认为问题在于声明:

res.Scan(&votes)

应该是:

res.Scan((*[]byte)(&votes))

除非您做出断言,否则您传递给 Scan 的 *Votes 不会被识别为 *[]byte。

这里有一个例子可以清楚地说明识别问题:

package main

import "fmt"

type BYTES []byte
func test(v interface{}) {
b, ok := v.(*[]byte)
fmt.Println(b, ok)
}

func main() {
p := BYTES("hello")
test(&p)
test((*[]byte)(&p))
}

上面的代码打印:

<nil> false
&[104 101 108 108 111] true

关于go - 为什么 `votes`的值在db.Prepare之后变了?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18131836/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com