无法将类型为字符串的变量userId用作结构体字面值中的整数值。

huangapple go评论66阅读模式
英文:

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

问题

我正在学习使用Go创建REST API。以下是我遇到的问题。

User结构体

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

逻辑部分

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

user := &user{
  ID: userId,
}

错误信息

无法将类型为string的userId变量用作结构体字面值中的int值

当用户发送GET请求时:

/user/:id

我尝试了相同的方法,但也返回了错误

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

错误信息

strconv.Atoi(userId)返回了两个值(int, error),但期望只有一个值
英文:

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

答案1

得分: 1

我找到了解决方案!我使用了strconv.Atoi()函数。

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

user := &user{
  ID: userId,
}
英文:

I found solution! I used strconv.Atoi()

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

user := &user{
  ID: userId,
}

答案2

得分: -2

我总是更喜欢使用cast.ToInt()将字符串转换为整数。

要导入cast包,请将以下行放在您的导入部分中:

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

user := &user{
      ID: userId,
}
英文:

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

huangapple
  • 本文由 发表于 2023年1月23日 18:39:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/75208323.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定