在Go应用程序中找不到接收函数。

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

Receiver function not being found in a Go application

问题

我正在努力弄清楚为什么在Go应用程序中找不到一个接收函数。

我将我的代码与其他教程代码进行比较,但是我无论如何都找不到问题所在。

在main.go中,我有一个名为application的结构体,并在main函数中创建了一个实例。

type application struct {
	cnf    cnf
	logger *log.Logger
}

....

func main {
...
app := &application{
		cnf:    cfg,
		logger: logger,
	}
...

在同一个main.go文件中,我有其他一些函数作为函数接收器,它们似乎工作正常,但是我在另一个文件中有一个函数,它位于main包中,具有以下签名

func (app *application) sendSlackMessage(msg string) error {}

但是,当我尝试从main中的另一个函数调用它时,像这样

err := app.sendSlackMessage(fmt.Sprintf("MESSAGE"))

我得到一个错误

app.sendSlackMessage未定义(*application类型没有字段或方法SendSlackMessage)

我不确定问题是否在于它在另一个文件中(尽管教程代码是这样做的),或者问题是什么。

英文:

I am struggling to work out why a receiver function in a go application isn't being found.

I'm comparing my code to other tutorial code as for the life of me can't see the problem.

I have a struct in main.go called application and am creating an instance of it in the main function.

type application struct {
	cnf    cnf
	logger *log.Logger
}

....

func main {
...
app := &application{
		cnf:    cfg,
		logger: logger,
	}
...

In the same main.go file I have other functions that are function receivers that seem to be working fine, but I have one function in a separate file, in package main with the signature

func (app *application) sendSlackMessage(msg string) error {}

but, when I try and call it from another function in main, like so

err := app.sendSlackMessage(fmt.Sprintf("MESSAGE"))

I get an error

app.sendSlackMessage undefined (type *application has no field or method SendSlackMessage)

I'm not sure if the issue is that its in another file (although the tutorial code does that) or what the issues is.

答案1

得分: 5

运行go run main.go将编译并执行 main.go 文件。该包中的任何其他 .go 文件将被忽略。

相反,尝试运行以下之一:

  • go run .
  • go run *.go
  • go run my/cmd
  • go build -o ./main && ./main

https://pkg.go.dev/cmd/go#hdr-Compile_and_run_Go_program

> Run 编译并运行指定的主 Go 包。通常,包被指定为一组来自单个目录的 .go 源文件,但它也可以是导入路径文件系统路径匹配单个已知包的模式,例如 'go run .' 或 'go run my/cmd'。

英文:

Running go run main.go will compile and execute only the main.go file. Any other .go files in that package will be left out.

Instead try running one of:

  • go run .
  • go run *.go
  • go run my/cmd
  • go build -o ./main && ./main

https://pkg.go.dev/cmd/go#hdr-Compile_and_run_Go_program

> Run compiles and runs the named main Go package. Typically the package
> is specified as a list of .go source files from a single directory,
> but it may also be an import path, file system path, or pattern
> matching a single known package
, as in 'go run .' or 'go run my/cmd'.

huangapple
  • 本文由 发表于 2021年8月3日 13:21:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/68630737.html
匿名

发表评论

匿名网友

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

确定