在Golang中,我可以限制某些包具有一组功能吗?

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

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)
}

除非提供了GetUrlGetPageName函数,并且函数签名正确,否则该包将无法编译。

英文:

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.

huangapple
  • 本文由 发表于 2017年1月29日 17:17:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/41919297.html
匿名

发表评论

匿名网友

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

确定