英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论