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.
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
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!