Search code examples
gogo-gormgo-gin

cannot use phone (type string) as type int in assignment


I have an error "cannot use phone (type string) as type int in assignment", how to fix this?

I use in github.com/gin-gonic/gin and github.com/jinzhu/gor

package main

import (
    "github.com/jinzhu/gorm"
    "github.com/gin-gonic/gin"
)

type Employees struct {
    gorm.Model
    Phone int
}

func (idb *InDB) CreateEmployees(c *gin.Context) {
    var (
        em models.Employees
        result gin.H
  )

  phone := c.PostForm("phone")
  em.Phone = phone

  result = gin.H {
        "result": em,
    }
    c.JSON(http.StatusOK, result)
}

Solution

  • Value in PostForm are all strings. You should declare phone as string type, or convert the phone number from string to integer. Like strconv.Atoi or strconv.ParseInt

    phone := c.PostForm("phone")
    phoneNumber, _ := strconv.Atoi(phone)
    em.Phone = phoneNumber