go

strconv.Itoa does not accept values of type int64


Im learning to create REST APIs using Go. Here's where I am stuck.

When user sends a CREATE request:

  1. From the Slice of articles, I need to take the last article
  2. Convert the ID(originally string) to Integer
  3. Increment the Integer and convert it back to string and save it

Article Struct

type Article struct {
    Id       string  `json:"id"`
    Title    string  `json:"title"`
    Desc     string  `json:"desc"`
    Content  string  `json:"content"`
}

Here's the logic

// 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,
        },
    }

ERROR

cannot use lastId (variable of type int64) as int value 
in argument to strconv.Itoa compiler (IncompatibleAssign)

Solution

  • Go has a strong typing system so Int32 and Int64 are not compatible type. Try to convert lastId into an int when calling Itoa:

        response := []Article{
            {
                Id: strconv.Itoa(int(lastId)),
                Title:   articleBody.Title,
                Desc:    articleBody.Desc,
                Content: articleBody.Content,
            },
        }
    

    Edit: As mention by @kostix in his answer, beware of overflows when converting int type (see his answer for details).
    A safer solution would be something like this:

    newId := int(lastId)
    if int64(newId) != lastId {
      panic("overflows!")
    }
    response := []Article{
                {
                    Id: strconv.Itoa(newId),
                    Title:   articleBody.Title,
                    Desc:    articleBody.Desc,
                    Content: articleBody.Content,
                },
     }