Golang无法将(类型*string)转换为类型string。

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

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.Usernameuser.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 != &quot;&quot; &amp;&amp; user.Password != &quot;&quot; {`



```pass := &amp;user.Password
password := []byte(*pass)```

Don&#39;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 `&amp;` and `*` from your code and it will probably work (except for this one: `ctx.Get(&quot;database&quot;).(*gorm.DB)`)

</details>



huangapple
  • 本文由 发表于 2017年1月14日 01:51:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/41640603.html
匿名

发表评论

匿名网友

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

确定