Golang类型断言 [英] Golang type assertion

查看:542
本文介绍了Golang类型断言的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经创建了一个基于字符串的字符串类型,现在我正试图通过实现Valuer和Scanner接口来使它与数据库驱动程序一起工作。



<$ p $ (值)(字符串))($角色)($角色)$($角色)

$ n

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

I继续收到错误:

  Go代码app / entities / user.go无法编译:无法转换值。 (type string)to type * Role 

我在这里做错了什么?

解决方案

这是第一个函数的工作代码:

  func(r * Role)Scan(value interface {})错误{
* r =角色(值。(字符串))
返回零
}

Alt你可能希望使用 s,ok:= value。(string)并返回!ok 的错误



driver.Valuer 的签名不是您给出的,而是: (r),$ n
$ b

  func b $ b} 

请注意,这不会处理或生成NULL值。



Playground


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

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.

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

这篇关于Golang类型断言的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆