无法运行非主程序包

这里是一个简单的 go 应用程序。如果我运行以下代码,就会出现“ go run: can not run non-main package”错误。

package zsdfsdf


import (
"fmt"
)


func Main() {
fmt.Println("sddddddd")
}

要修复它,我只需要将包命名为 main。但我不明白我为什么要这么做。我应该可以给包裹取任何我想要的名字。

另一个问题,我知道主函数是程序的入口点,你需要它。否则它不会工作。但是我看到一些没有主要功能的代码仍然可以工作。

点击这个链接,页面底部的示例没有使用包 main 和 main 函数,它仍然可以工作。只是好奇为什么。

Https://developers.google.com/appengine/docs/go/gettingstarted/usingdatastore

106149 次浏览

You need to specify in your app.yaml file what your app access point is. Take a look here. You need to specify:

application: zsdfsdf

Also see from that above link:

"Note: When writing a stand-alone Go program we would place this code in package main. The Go App Engine Runtime provides a special main package, so you should put HTTP handler code in a package of your choice (in this case, hello)."

You are correct that all Go programs need the Main method. But it is provided by Google App Engine. That is why your provided example works. Your example would not work locally (not on GAE).

The entry point of each go program is main.main, i.e. a function called main in a package called main. You have to provide such a main package.

GAE is an exception though. They add a main package, containing the main function automatically to your project. Therefore, you are not allowed to write your own.

You need to use the main package, a common error starting with go is to type

package Main

instead of

package main

A Solution to avoid this error is defining entry point somefilename.go file as main package by adding package main as the first line of the entry point

package main


// import statements
import "fmt"


// code below

To avoid the problem you can modify the code as follow

package main


import (
"fmt"
)


func main() {
fmt.Println("sddddddd")
}

rename the package as "main" and rename the function as "main" instead of "Main".