覆盖匿名结构函数

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

Overwrite anonymous struct function

问题

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

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

package base

import (
	"fmt"
	"net/http"
)

type Executer interface {
	Execute()
}

type Controller struct { }

func (self *Controller) Execute() {
	fmt.Println("Hello Controller")
}

func (self *Controller) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
    self.Execute()
}

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

package base

import (
	"fmt"
	"net/http"
	"net/http/httptest"
	"testing"
)

type Test struct {
	Controller
}

func (self *Test) Execute() {
	fmt.Println("Hello Test")
}

func TestInheritance(t *testing.T) {
	ts := httptest.NewServer(&Test{})
	defer ts.Close()
	http.Get(ts.URL)
}

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

英文:

How can I overwrite anonymous struct function.

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

package base

import (
	"fmt"
	"net/http"
)

type Executer interface {
	Execute()
}

type Controller struct { }
    
func (self *Controller) Execute() {
	fmt.Println("Hello Controller")
}
       
func (self *Controller) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
    self.Execute()
}

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

package base

import (
	"fmt"
	"net/http"
	"net/http/httptest"
	"testing"
)

type Test struct {
	Controller
}

func (self *Test) Execute() {
	fmt.Println("Hello Test")
}

func TestInheritance(t *testing.T) {
	ts := httptest.NewServer(&Test{})
	defer ts.Close()
	http.Get(ts.URL)
}

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

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

type Test struct {
    Controller
}

`Controller` 没有 `ServeHTTP` 方法 `*Controller` 所以

type Test struct {
    *Controller
}

我认为这样会起作用
英文:
type Test struct {
    Controller
}

Controller has no ServeHTTP method but *Controller has. So

type Test struct {
    *Controller
}

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:

确定