英文:
exported methods not available in same package
问题
我有一个小的Go语言项目,其中的main.go文件中有几个处理程序,这些处理程序引用了session.go文件中与会话相关的方法。两个文件的顶部都有package main
。session.go文件中的函数都以大写字母开头(即它们是公共/导出的方法)。然而,当我运行main.go文件时,它显示从main.go调用的session.go中的方法是"未定义"的。为什么会这样,如何修复呢?
我是这样运行项目的:go run main.go
main.go
func logout(w http.ResponseWriter, r *http.Request) {
ClearSession(w, r)
....
}
session.go
func ClearSession(w http.ResponseWriter, r *http.Request) {
}
英文:
I have a small go lang project which in the main.go file has a few handlers that refer to session related methods in a session.go file. Both have package main
at the top of the file. The functions in the session.go file all begin with an uppercase letter (i.e. they are public/exported methods). Yet when I run the main.go
file, it says the methods located in session.go
and called from main.go
are undefined
. Why is that, how to fix it.
I am running the project like go run main.go
main.go
func logout(w http.ResponseWriter, r *http.Request) {
ClearSession(w, r)
....
}
session.go
func ClearSession(w http.ResponseWriter, r *http.Request) {
}
答案1
得分: 1
如@ptd所说,该命令需要所有以指定名称命名的文件。
我更喜欢使用另一个包:
/ main.go
|_session/
|_session.go
|_validations.go
|_errors.go
这样,你可以组织你的代码并简化你的命名文件。
例如:
文件:main.go
package main
import "session"
func main() {
var validator session.Validator
var session session.Session
...
if session.IsValid() == false {
// 返回 session.InvalidSession
fmt.Printf("ERROR: %v", session.InvalidSession)
}
}
文件:errors.go
import "errors"
var (
InvalidSession = errors.New("[你的错误消息]"
)
然后你可以使用:
go run main.go
英文:
As @ptd said, the command needs all the files named.
I prefer use another package:
/ main.go
|_session/
|_session.go
|_validations.go
|_errors.go
So, you can organize your code and simplify your named files.
e.g.:
file: main.go
package main
import "session"
func main() {
var validator session.Validator
var session session.Session
...
if session.IsValid() == false {
// return session.InvalidSession
fmt.Printf("ERROR: %v", session.InvalidSession)
}
}
file: errors.go
import "errors"
var (
InvalidSession = errors.New("[Your error message]"
)
Then you can use:
go run main.go
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论