go - 将方法与返回 "self"的结构相关联

标签 go

我知道 Go 没有传统的 OOP 概念。但是,我很想知道是否有更好的方法来设计“构造函数”,就像我在下面的代码片段中所做的那样:

type myOwnRouter struct {
}

func (mor *myOwnRouter) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Hello from my own Router!")
}

func newMyOwnRouter() *myOwnRouter {
    return &myOwnRouter{}
}

func init() {
    http.Handle("/", newMyOwnRouter())
    ...
}

我基本上想摆脱“独立”的 newMyOwnRouter() 函数并将其作为结构本身的一部分,例如我希望能够执行类似的操作:

http.Handle("/", myOwnRouter.Router)

这可行吗?

最佳答案

事实上的标准模式是一个函数调用 New

package matrix
function NewMatrix(rows, cols int) *matrix {
    m := new(matrix)
    m.rows = rows
    m.cols = cols
    m.elems = make([]float, rows*cols)
    return m
}

当然构造函数必须是Public函数,才能在包外调用。

关于构造函数模式的更多信息 here

在你的情况下,你想要一个 Sigleton 包,那么这就是模式:

package singleton

type myOwnRouter struct {
}

var instantiated *myOwnRouter = nil

func NewMyOwnRouter() * myOwnRouter {
    if instantiated == nil {
        instantiated = new(myOwnRouter);
    }

    return instantiated;
}

关于go - 将方法与返回 "self"的结构相关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21958229/

相关文章:

string - 在 Go 中执行 http 请求时字符串出现乱码

go - 仅知道资源种类/类型时创建空的 Kubernetes 资源结构(在 golang 中)

javascript - 将 Go 函数传递给 html/js 按钮 "onclick"响应

macos - 如何在 os x、centos 6 上构建 goncurses

go - dynamodbattribute.MarshalMap 返回空 map

go - goroutine调用中 channel 接收运算符的阻塞行为

go - 如何在 Go 中 gc 互斥映射?

mongodb - chrome 和 safari 不会在设置了 Content-Length 的 go 服务器提供的 html 模板中呈现图像

http - 如何非破坏性地检查 HTTP 客户端是否已关闭连接?

c++ - D 是否适合编写跟踪 JIT 编译器?