我正在学习使用 Go 创建 REST API。这就是我被困住的地方。
当用户发送 CREATE 请求时:
文章结构
type Article struct {
Id string `json:"id"`
Title string `json:"title"`
Desc string `json:"desc"`
Content string `json:"content"`
}
Run Code Online (Sandbox Code Playgroud)
这是逻辑
// get the last id and convert it to integer and increment
lastId, err := strconv.ParseInt(Articles[len(Articles) - 1].Id, 10, 64)
lastId = lastId + 1
if err != nil {
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
}
response := []Article{
{
Id: strconv.Itoa(lastId),// ERROR
Title: articleBody.Title,
Desc: articleBody.Desc,
Content: articleBody.Content,
},
}
Run Code Online (Sandbox Code Playgroud)
cannot use lastId (variable of type int64) as int value
in argument to strconv.Itoa compiler (IncompatibleAssign)
Run Code Online (Sandbox Code Playgroud)
Go 有一个强大的类型系统,因此 Int32 和 Int64 不是兼容的类型。调用Itoa时尝试转换lastId成an :int
response := []Article{
{
Id: strconv.Itoa(int(lastId)),
Title: articleBody.Title,
Desc: articleBody.Desc,
Content: articleBody.Content,
},
}
Run Code Online (Sandbox Code Playgroud)
编辑:正如 @kostix 在他的答案中提到的,在转换 int 类型时要小心溢出(有关详细信息,请参阅他的答案)。
更安全的解决方案是这样的:
newId := int(lastId)
if int64(newId) != lastId {
panic("overflows!")
}
response := []Article{
{
Id: strconv.Itoa(newId),
Title: articleBody.Title,
Desc: articleBody.Desc,
Content: articleBody.Content,
},
}
Run Code Online (Sandbox Code Playgroud)