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

its*_*ali 3 string type-conversion go

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

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

shi*_*roy 5

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

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

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

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

开始通过删除所有修复此问题&,并*从你的代码,它可能会工作(除了这一个:ctx.Get("database").(*gorm.DB)

  • 没问题。祝你好运!通常,在编译器告诉您需要之前,您不必太担心指针。这并不完全正确,但你会掌握它的窍门。 (3认同)