简体   繁体   English

Golang类型断言

[英]Golang type assertion

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 我已经创建了一个基于字符串的类型的角色,我现在试图通过实现Valuer和Scanner接口来使它与数据库驱动程序一起工作

type Role string

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

    return nil
}

func (r *Role) Value(value driver.Value, err error) {
    if err != nil {
        value = string(r)
    }
}

I keep getting the error: 我一直收到错误:

The Go code app/entities/user.go does not compile: cannot convert value.(string) (type string) to type *Role

What am I doing wrong here? 我在这做错了什么?

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. 虽然你可能希望使用s, ok := value.(string)并为!ok而不是panicing返回错误。

The signature for the a driver.Valuer is not what you gave but: 一个driver.Valuer的签名不是你给的,但是:

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

Note this doesn't handle or produce NULL values. 请注意,这不会处理或生成NULL值。

Playground 操场

I don't think it's a good idea to modify the receiver of your method (r) in the Scan method. 我不认为在Scan方法中修改方法(r)的接收器是个好主意。

You need a type assertion to convert value interface{} to string. 您需要一个类型断言来将value interface{}转换为string。
You are trying to convert a string to a pointer to Role . 您正在尝试将string转换为pointer to Rolepointer 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 应该管用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM