Golang中可能存在的结构体bug探讨
Golang中可能存在的结构体bug探讨 你好。我有多个结构体类型,所有字段似乎都正确填充了,但有一个字段除外。我不明白为什么当我在参数中传入1时,该值显示为0。
package main
import (
"fmt"
)
type convFlow struct {
conFlowData []*userData
//choices []*choice
}
type convMessage struct {
botMsg int
userMsg int
}
//ConvChat general info about chat user
type userData struct {
userID int
state int
msgIDs *convMessage
userName string
userFname string
userLastName string
}
func (data *convFlow) addData(userID int, state int, botMsg, userMsg int, userName, userFname, userLastName string) {
usr := &userData{
userID: userID,
msgIDs: &convMessage{
botMsg: botMsg,
userMsg: userMsg,
},
userName: userName,
userFname: userFname,
userLastName: userLastName,
}
data.conFlowData = append(data.conFlowData, usr)
}
func main() {
start := new(convFlow)
start.addData(222314, 1, 12, 13, "@Brandon", "John", "Don")
for _, dt := range start.conFlowData {
fmt.Println(dt.state)
}
}
有人知道为什么它显示0而不是1吗?
更多关于Golang中可能存在的结构体bug探讨的实战教程也可以访问 https://www.itying.com/category-94-b0.html
2 回复
在你的代码中,state 字段没有被正确赋值。在 addData 方法中,你传入了 state 参数,但在初始化 userData 结构体时,没有将其赋值给 state 字段。因此,state 字段保留了其零值(0)。
以下是修正后的代码:
package main
import (
"fmt"
)
type convFlow struct {
conFlowData []*userData
}
type convMessage struct {
botMsg int
userMsg int
}
type userData struct {
userID int
state int
msgIDs *convMessage
userName string
userFname string
userLastName string
}
func (data *convFlow) addData(userID int, state int, botMsg, userMsg int, userName, userFname, userLastName string) {
usr := &userData{
userID: userID,
state: state, // 添加此行以正确赋值 state 字段
msgIDs: &convMessage{
botMsg: botMsg,
userMsg: userMsg,
},
userName: userName,
userFname: userFname,
userLastName: userLastName,
}
data.conFlowData = append(data.conFlowData, usr)
}
func main() {
start := new(convFlow)
start.addData(222314, 1, 12, 13, "@Brandon", "John", "Don")
for _, dt := range start.conFlowData {
fmt.Println(dt.state) // 现在输出 1
}
}
关键修改是在初始化 userData 结构体时添加了 state: state,确保传入的 state 参数被正确赋值给结构体的 state 字段。

