英文:
Golang Cannot Convert (type *string) to type string
问题
当我尝试编译以下代码时,我得到了以下错误:
users.go:31: 无法将 pass(类型为 *string)转换为 string 类型
users.go:78: 无法将 &user.Password(类型为 *string)转换为 []byte 类型
我该如何取消引用或将指针转换为字符串字面值?
提前感谢。
我正在尝试编译的代码:https://play.golang.org/p/gtMKLNAyNk
英文:
When I tried to compile the following code I get following errors:
users.go:31: cannot convert pass (type *string) to type string
users.go:78: cannot convert &user.Password (type *string) to type []byte
How do I dereference or convert the pointer to the string literal?
Thanks in advance.
code which I am trying to compile: https://play.golang.org/p/gtMKLNAyNk
答案1
得分: 6
第9行的if语句需要修改。user.Username
和user.Password
是字符串,因此它们永远不会为nil。你需要检查的是空字符串,像这样:if user.Username != "" && user.Password != "" {
password := []byte(*pass)```
不要取`user.Password`的地址。只需使用`password := []byte(user.Password)`
基本上,你的所有问题都是这个主题的变体。
通过从代码中删除所有的`&`和`*`来开始解决这个问题,它可能会正常工作(除了这个问题:`ctx.Get("database").(*gorm.DB)`)。
<details>
<summary>英文:</summary>
The if on line 9 needs to change I think. `user.Username` and `user.Password` are strings so they will never be nil. What you need to check instead is for empty string like this: `if user.Username != "" && user.Password != "" {`
```pass := &user.Password
password := []byte(*pass)```
Don't take the address of user.Password. Just use `password := []byte(user.Password)`
Basically all of your issues are variations on that theme.
Start fixing this issue by removing all `&` and `*` from your code and it will probably work (except for this one: `ctx.Get("database").(*gorm.DB)`)
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论