亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

斯特里康夫Itoa 不接受 int64 類型的值

斯特里康夫Itoa 不接受 int64 類型的值

Go
繁星點點滴滴 2022-09-26 17:24:14
我正在學習使用 Go 創建 REST API。這就是我被困住的地方。當用戶發送創建請求時:從文章的片段中,我需要采取最后一篇文章將 ID(原字符串)轉換為整數遞增整數并將其轉換回字符串并保存文章結構type Article struct {    Id       string  `json:"id"`    Title    string  `json:"title"`    Desc     string  `json:"desc"`    Content  string  `json:"content"`}邏輯如下// 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,        },    }錯誤cannot use lastId (variable of type int64) as int value in argument to strconv.Itoa compiler (IncompatibleAssign)
查看完整描述

2 回答

?
白板的微信

TA貢獻1883條經驗 獲得超3個贊

Go 有一個強大的類型系統,因此 Int32 和 Int64 不是兼容的類型。嘗試在調用 Itoa 時轉換為:lastIdint


    response := []Article{

        {

            Id: strconv.Itoa(int(lastId)),

            Title:   articleBody.Title,

            Desc:    articleBody.Desc,

            Content: articleBody.Content,

        },

    }

編輯:正如@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,

            },

 }


查看完整回答
反對 回復 2022-09-26
?
不負相思意

TA貢獻1777條經驗 獲得超10個贊

語言規范

uint大小
為 32 位或 64 位intuint

這意味著,在特定平臺/版本的 Go 上,Go 的大小可能與 相同,這就是 Go 不會靜默地允許您將 type 的值作為 type 的參數傳遞的原因。intint32int64int

此外,另一個答案中建議的普通類型轉換應該謹慎對待:當你的程序被編譯并最終在編譯的代碼中具有32位大小時會發生什么,并且特定值超出了有符號的32位整數支持的數字范圍,例如2,147,483,648?
同樣,規范int(lastId)intlastId

在整數類型之間轉換時,如果值為有符號整數,則符號擴展到隱式無限精度;否則,它是零擴展。然后將其截斷以適合結果類型的大小。例如,如果 ,則 .轉換始終產生有效值;沒有溢出的跡象。v := uint16(0x10F0)uint32(int8(v)) == 0xFFFFFFF0

因此,代碼


var i64 int64 = 2_147_483_648

var i32 = int32(i64)

fmt.Println(i32)

指紋


-2147483648

當此值傳遞給 時,它將返回“-2147483648” - 很可能不是您所期望的。strconv.Itoa


因此,在健壯的代碼中,在執行此類類型轉換時應注意,并檢查轉換后的值是否健全,例如


v := int(lastId)

if int64(v) != lastId {

  panic("ouch!")

}

或者僅僅通過strconv使用最大的方便類型。格式。


查看完整回答
反對 回復 2022-09-26
  • 2 回答
  • 0 關注
  • 172 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號