Go需要逗号,放在那里会抛出其他不相关的错误

Go requires comma, when put there, other unrelated errors are thrown

我正在尝试使用 this 库在 Golang 中创建一个 reddit 机器人,Golang 要求一个逗号,但是,当我把它放在那里时,Go 会抛出其他错误。

这是我的 main.go:

package main

import (
  "github.com/turnage/graw/reddit"
)

func main() {
  cfg := BotConfig{
    Agent: "graw:doc_demo_bot:0.3.1 by /u/yourusername",
    // Your registered app info from following:
    // https://github.com/reddit/reddit/wiki/OAuth2
    App: App{
      ID:     "sdf09ofnsdf",
      Secret: "skldjnfksjdnf",
      Username: "yourbotusername",
      Password: "yourbotspassword",
    }
  }
  bot, _ := NewBot(cfg)
  bot.SendMessage("roxven", "Thanks for making this Reddit API!", "It's ok.")
}

这是上面代码的输出(17:7 处没有逗号):

# command-line-arguments
./main.go:17:6: syntax error: unexpected newline, expecting comma or }

这是我将逗号放在那里时的输出:

# command-line-arguments
./main.go:4:3: imported and not used: "github.com/turnage/graw/reddit"
./main.go:8:10: undefined: BotConfig
./main.go:19:13: undefined: NewBot

我也试过在第 16 行后加一个逗号(这样就有两个),但我得到了这个错误:

# command-line-arguments
./main.go:16:36: syntax error: unexpected comma, expecting expression
./main.go:17:6: syntax error: unexpected newline, expecting comma or }

我不确定我做错了什么。

你可以在

之后加上一个,
App: App{
  ID:     "sdf09ofnsdf",
  Secret: "skldjnfksjdnf",
  Username: "yourbotusername",
  Password: "yourbotspassword",
}, //like this

其他错误实际上是您需要修复的错误。 Golang 是严格的,不允许未使用的导入或未使用的变量。此外,您必须导入包含您使用的结构定义的包 - BotConfigNewBot.

您可以为您的导入命名,这样您就可以引用您的导入而无需执行 reddit.BotConfig。对于前

import r "github.com/turnage/graw/reddit"

这将允许您简单地使用 r.BotConfig for ex。否则,每次你想使用 BotConfig 时,你都必须将包名称引用为 reddit.BotConfig

您的错误(通过添加逗号修复语法问题后)都是相互关联的。正如所写,您 没有 使用您导入的包。使用 reddit.BotConfigreddit.Appreddit.NewBot 以使用该包中的结构和函数。在 Go 中导入不会将事物带入全局顶级命名空间。

func main() {
    cfg := reddit.BotConfig{
        Agent: "graw:doc_demo_bot:0.3.1 by /u/yourusername",
        // Your registered app info from following:
        // https://github.com/reddit/reddit/wiki/OAuth2
        App: reddit.App{
            ID:       "sdf09ofnsdf",
            Secret:   "skldjnfksjdnf",
            Username: "yourbotusername",
            Password: "yourbotspassword",
        },
    }
    bot, _ := reddit.NewBot(cfg)
    bot.SendMessage("roxven", "Thanks for making this Reddit API!", "It's ok.")
}