英文:
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 值。
英文:
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.
答案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 = &rx
_ = rx // just to silence the compiler for this demonstration
_ = rx2 // just to silence the compiler for this demonstration
return rx, nil
}
should work
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论