Golang type assertion

后端 未结 2 1150
挽巷
挽巷 2021-01-07 19:13

I have created a type Role based off string, and I am now trying to get it to work with the database driver by implementing the Valuer and Scanner interfaces



        
相关标签:
2条回答
  • 2021-01-07 19:41

    Here is working code for the first function:

    func (r *Role) Scan(value interface{}) error {
        *r = Role(value.(string))
        return nil
    }
    

    Although you may wish to use s, ok := value.(string) and return an error for !ok instead of panic-ing.

    The signature for the a driver.Valuer is not what you gave but:

    func (r Role) Value() (driver.Value, error) {
        return string(r), nil
    }
    

    Note this doesn't handle or produce NULL values.

    Playground

    0 讨论(0)
  • 2021-01-07 20:05

    I don't think it's a good idea to modify the receiver of your method (r) in the Scan method.

    You need a type assertion to convert value interface{} to string.
    You are trying to convert a string to a pointer to Role.

    func (r *Role) Scan(value interface{}) (retVal Role, err error) {
        var s string;
    
        if v,ok := value.(string); ok {
          s = v;
        }
        var rx Role
        rx = Role(s)
    
        var rx2 *Role
        rx2 = &rx
        _ = rx // just to silence the compiler for this demonstration
        _ = rx2 // just to silence the compiler for this demonstration
        return rx, nil
    }
    

    should work

    0 讨论(0)
提交回复
热议问题