Golang类型断言

huangapple go评论83阅读模式
英文:

Golang type assertion

问题

我已经创建了一个基于字符串的Role类型,并且现在我正在尝试通过实现Valuer和Scanner接口使其与数据库驱动程序配合工作。

type Role string

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

    return nil
}

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

我一直收到以下错误:

无法将value.(string)(类型为string)转换为*Role类型

我在这里做错了什么?

英文:

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?

答案1

得分: 24

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

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

尽管你可能希望使用 s, ok := value.(string) 并且对于 !ok 返回一个错误而不是 panic。

driver.Valuer 的签名不是你给出的,而是:

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

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

Playground

英文:

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.

<kbd>Playground</kbd>

答案2

得分: 4

我认为在Scan方法中修改接收者(r)不是一个好主意。

你需要使用类型断言将value interface{}转换为字符串。
你正在尝试将一个string转换为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 // 仅为了在此演示中使编译器静默
    _ = rx2 // 仅为了在此演示中使编译器静默
    return rx, nil
}

应该可以工作。

英文:

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 = &amp;rx
    _ = rx // just to silence the compiler for this demonstration
    _ = rx2 // just to silence the compiler for this demonstration
    return rx, nil
}

should work

huangapple
  • 本文由 发表于 2014年1月5日 22:46:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/20934909.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定