【问题标题】:Golang Cannot Convert (type *string) to type stringGolang 无法将(类型 *string)转换为类型字符串
【发布时间】:2017-01-13 17:51:57
【问题描述】:

当我尝试编译以下代码时,出现以下错误:

users.go:31: cannot convert pass (type *string) to type string

users.go:78: cannot convert &user.Password (type *string) to type []byte

如何取消引用或将指针转换为字符串文字?

提前致谢。

我正在尝试编译的代码:https://play.golang.org/p/gtMKLNAyNk

【问题讨论】:

  • 除了您的 sn-p 之外,您还可以发布给您带来问题的确切行吗?线条不匹配,因此很难知道问题出在哪里。
  • 还将 models.User 结构定义添加到您的 sn-p,可能会有所帮助
  • 您一直在不必要地获取该代码中事物的地址。提示,&user.Username 永远不会是 nil
  • @JimB 对这个指针很陌生,然后去:)

标签: string go type-conversion


【解决方案1】:

我认为第 9 行的 if 需要更改。 user.Usernameuser.Password 是字符串,所以它们永远不会为零。您需要检查的是这样的空字符串:if user.Username != "" && user.Password != "" {

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

不要取user.Password的地址。只需使用password := []byte(user.Password)

基本上,您的所有问题都是该主题的变体。

通过从您的代码中删除所有&* 开始解决此问题,它可能会起作用(除了这个:ctx.Get("database").(*gorm.DB)

【讨论】:

  • 没问题。祝你好运!通常,在编译器告诉您需要之前,您不必过多担心指针。这并不完全正确,但你会掌握它的窍门。
猜你喜欢
  • 1970-01-01
  • 2013-01-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多