Home  >  Article  >  Backend Development  >  Cannot use userId (variable of type string) as an int value in a struct literal

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

PHPz
PHPzforward
2024-02-10 19:21:19706browse

无法使用 userId(字符串类型的变量)作为结构文字中的 int 值

In PHP programming, it is often encountered that string type variables are used as integer values. However, according to the syntax rules of PHP, we cannot directly use a string type variable as an integer value, which will lead to incorrect results. This question often confuses beginners. Therefore, PHP editor Yuzi brings you a solution to this problem. Next, we will explain in detail how to correctly convert a string type variable to an integer value so that it can be used correctly in the program.

Question content

I am learning to use go to create rest api. This is where I'm stuck.

User structure

type user struct {
  id         int    `json:"id"`
  firstname  string `json:"first_name"`
  lastname   string `json:"last_name"`
}

The logic is as follows

params := httprouter.paramsfromcontext(r.context())
userid := params.byname("id")

user := &user{
  id: userid,
}

mistake

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

When the user sends a get request:

/user/:id

I tried the same but it also returned the error

user := &user{
  id: strconv.atoi(int(userid)),
}

mistake

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

Solution

I found the solution! I used strconv.atoi()

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

user := &user{
  ID: userId,
}

The above is the detailed content of Cannot use userId (variable of type string) as an int value in a struct literal. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete