我从服务器收到一条消息,如[0,“on”,[6,1,5,“market”,45.7]],并将其保存到[]interface{}变量。我想用这个数组的值初始化结构。我对Go来说是全新的,并尝试这样做:
import "golang.org/x/net/websocket"
...
var msg []interface{}
// Server send response: `[0,"on",[6,1,5,"market",45.7]]`
if err := websocket.Message.Receive(ws, &msg); err != nil {
logger.Println(err)
} else {
type Order struct {
ID int32,
GID int32,
CID int32,
Type string,
Amount float64
}
// here msg is [0,"on",[6,1,5,"market",45.7]]
switch msg[1] {
case "on":
if rawOrder, ok := msg[2].([]interface{}); ok {
order := Order{int32(rawOrder[0]), int32(rawOrder[1]), int32(rawOrder[2]), string(rawOrder[3]), float64(rawOrder[4])}
}
}
但是我收到一个错误“无法将'interface{}'类型的表达式转换为'int32'”类型,下一步是为每个rawOrder[i]类型使用switch,但它太长了。我怎样才能轻松做到?
RISEBY
相关分类