英文:
Can I restrict packages have some set of functions in Golang?
问题
我有一些功能类似的包,它们都是用于处理网络请求的。
在每个包中,我有类似以下的用于处理主页的函数:
package home_page_handler
func GetUrl() string {
return "/"
}
func GetPageName() string {
return "HomePage"
}
为了更好地组织代码,我想知道是否可以通过接口来添加限制,使得每个包中的某个“类”包含这些函数?
这样,如果我添加了另一个处理程序,如果缺少一个函数或者函数签名错误,在编译时就会抛出错误。
英文:
I have packages, that are similar in functionality, as they are web request handlers.
I have functions like this for Home page in each package:
package home_page_handler
func GetUrl() string {
return "/"
}
func GetPageName() string {
return "HomePage"
}
To structure the code better, I wonder if I can add a restriction, may be via interfaces to make each package of some "class" contain these functions?
That way if I add one more handler, it will throw an error while compiling if a function is missing or has a wrong signature.
答案1
得分: 1
你可以通过调用RegisterHandler
函数来“注册”每个包。
package server
type PageHandler struct {
url, name func() string
}
var Handlers = []PageHandler
func RegisterHandler(url func() string, name func() string) {
Handlers = append(Handlers, PageHandler{url, name})
}
...
package home_page
...
func init() {
server.RegisterHandler(GetUrl, GetPageName)
}
除非提供了GetUrl
和GetPageName
函数,并且函数签名正确,否则该包将无法编译。
英文:
You could "register" each package with a call
package server
type PageHandler {
url, name func() string
}
var Handlers = []PageHandler
func RegisterHandler(url func()string, name func()string) {
Handlers = append(Handlers, PageHandler{url, name})
}
...
package home_page
...
func init() {
server.RegisterHandler(GetUrl, GetPageName)
}
The package won't compile unless GetUrl
and GetPageName
are provided and the function signature is correct.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论