NewIpcServer
接收可由價值型或指針式滿足接口的(Handle method has pointer receiver)
package ipc
import (
"testing"
)
// import (
// "encoding/json"
// "fmt"
//)
type Request struct {
Method string `json/"method"`
Params string `json/"params"`
}
type Response struct {
Code string `json/"code"`
Body string `json/"body"`
}
type Server interface {
Name() string
Handle(method, params string) *Response
}
type IpcServer struct {
Server
}
func NewIpcServer(server Server) *IpcServer {
return &IpcServer{server}
}
type EchoServer struct {
}
func (server *EchoServer) Name() string {
return "EchoServer"
}
func (server *EchoServer) Handle(method, params string) *Response {
return &Response{"OK", "Echo " + method + " " + params}
}
func TestIpc(t *testing.T) {
server := EchoServer{}
ipcServer := NewIpcServer(server)
}
意義。
由於EchoServer
實現了作爲指針型接收器(例如func (server *EchoServer) ...
)的接口功能,所以您必須將指針傳遞給NewIpcServer
函數。
在你TestIpc
職能轉變server
是一個指針作爲這樣
server := new(EchoServer)
和測試應編譯就好了。