Home > Software engineering >  Cannot use userId (variable of type string) as int value in struct literal
Cannot use userId (variable of type string) as int value in struct literal

Time:01-24

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

User Struct

type user struct {
  ID         int    `json:"id"`
  FirstName  string `json:"first_name"`
  LastName   string `json:"last_name"`
}

Here's the logic

params := httprouter.ParamsFromContext(r.Context())
userId := params.ByName("id")

user := &user{
  ID: userId,
}

ERROR

cannot use userId (variable of type string) as int value in struct literal

When user sends a get request:

/user/:id

I tryed same this but it's return error also

user := &user{
  ID: strconv.Atoi(int(userId)),
}

Error

2-valued strconv.Atoi(int(userId)) (value of type (int, error)) where single value is expected

CodePudding user response:

I found solution! I used strconv.Atoi()

userId, err := strconv.Atoi(params.ByName("id"))
if err != nil {
  fmt.Println(err)
}

user := &user{
  ID: userId,
}

CodePudding user response:

I always prefer cast.ToInt() to convert a string into an int.

To import the cast package. place the below line in your import section

"github.com/spf13/cast"
userId := cast.ToInt(params.ByName("id"))

user := &user{
      ID: userId,
}
  •  Tags:  
  • go
  • Related