覆盖匿名结构函数

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

Overwrite anonymous struct function

问题

如何覆盖匿名结构体函数。

为了澄清我的意思,请看下面的代码片段:

  1. package base
  2. import (
  3. "fmt"
  4. "net/http"
  5. )
  6. type Executer interface {
  7. Execute()
  8. }
  9. type Controller struct { }
  10. func (self *Controller) Execute() {
  11. fmt.Println("Hello Controller")
  12. }
  13. func (self *Controller) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
  14. self.Execute()
  15. }

现在我将Controller结构体嵌入到Test结构体中,也称为匿名结构体。

  1. package base
  2. import (
  3. "fmt"
  4. "net/http"
  5. "net/http/httptest"
  6. "testing"
  7. )
  8. type Test struct {
  9. Controller
  10. }
  11. func (self *Test) Execute() {
  12. fmt.Println("Hello Test")
  13. }
  14. func TestInheritance(t *testing.T) {
  15. ts := httptest.NewServer(&Test{})
  16. defer ts.Close()
  17. http.Get(ts.URL)
  18. }

输出结果是"Hello Controller",但期望的是"Hello Test"。你可以看到上面的代码,我重新实现了Execute函数,但它不起作用。

英文:

How can I overwrite anonymous struct function.

To clarify what I mean look at the following code snippet:

  1. package base
  2. import (
  3. "fmt"
  4. "net/http"
  5. )
  6. type Executer interface {
  7. Execute()
  8. }
  9. type Controller struct { }
  10. func (self *Controller) Execute() {
  11. fmt.Println("Hello Controller")
  12. }
  13. func (self *Controller) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
  14. self.Execute()
  15. }

Now I am embedding the Controller struct into Test struct, also called anonymous

  1. package base
  2. import (
  3. "fmt"
  4. "net/http"
  5. "net/http/httptest"
  6. "testing"
  7. )
  8. type Test struct {
  9. Controller
  10. }
  11. func (self *Test) Execute() {
  12. fmt.Println("Hello Test")
  13. }
  14. func TestInheritance(t *testing.T) {
  15. ts := httptest.NewServer(&Test{})
  16. defer ts.Close()
  17. http.Get(ts.URL)
  18. }

As output I've got "Hello Controller" but expected "Hello Test". You can see code above, I reimplement the execute function, but it does not work.

答案1

得分: 4

由于Test没有ServeHTTP方法,你的测试服务器使用了Controller的方法,该方法调用了Controller.Execute()。如果你希望它正常工作,请为Test类型定义ServeHTTP方法。

英文:

Since Test has no ServeHTTP method, your test server uses Controller's, which calls Controller.Execute(). If you want it to work properly, define ServeHTTP for the Test type.

答案2

得分: -1

你好!以下是翻译好的内容:

  1. type Test struct {
  2. Controller
  3. }
  4. `Controller` 没有 `ServeHTTP` 方法 `*Controller` 所以
  5. type Test struct {
  6. *Controller
  7. }
  8. 我认为这样会起作用
英文:
  1. type Test struct {
  2. Controller
  3. }

Controller has no ServeHTTP method but *Controller has. So

  1. type Test struct {
  2. *Controller
  3. }

I think it will work.

huangapple
  • 本文由 发表于 2014年11月12日 20:30:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/26887067.html
匿名

发表评论

匿名网友

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

确定