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

PHPz
Release: 2024-02-10 19:21:19
forward
745 people have browsed it

无法使用 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"`
}
Copy after login

The logic is as follows

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

user := &user{
  id: userid,
}
Copy after login

mistake

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

When the user sends a get request:

/user/:id
Copy after login

I tried the same but it also returned the error

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

mistake

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

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,
}
Copy after login

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!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template