dougui1977 2016-10-02 04:01
浏览 54
已采纳

由于指针接收器,无法实现Go接口[重复]

My go test can not be passed. What's wrong? What's the meaning of (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)
}

When I run go test ipc_test.go

/ipc_test.go:49: cannot use server (type EchoServer) as type Server in argument to NewIpcServer:
    EchoServer does not implement Server (Handle method has pointer receiver)
FAIL    command-line-arguments [build failed]
</div>
  • 写回答

2条回答 默认 最新

  • dsjq62428 2016-10-02 04:13
    关注

    1- You may use

    server := &EchoServer{}
    

    instead of

    server := EchoServer{}
    

    Method sets:

    A type may have a method set associated with it. The method set of an interface type is its interface. The method set of any other type T consists of all methods declared with receiver type T. The method set of the corresponding pointer type *T is the set of all methods declared with receiver *T or T (that is, it also contains the method set of T). Further rules apply to structs containing anonymous fields, as described in the section on struct types. Any other type has an empty method set. In a method set, each method must have a unique non-blank method name.

    And see: Pointer receiver and Value receiver difference in implementation with Iris framework


    2- Or you may use

    func (server EchoServer) Name() string {
        return "EchoServer"
    }
    
    func (server EchoServer) Handle(method, params string) *Response {
        return &Response{"OK", "Echo " + method + " " + params}
    }
    

    with

    server := EchoServer{}
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 鼠标右键,撤销删除 复制 移动,要怎样删除
  • ¥15 使用MATLAB进行余弦相似度计算加速
  • ¥15 服务器安装php5.6版本
  • ¥15 我想用51单片机和数码管做一个从0开始的计数表 我写了一串代码 但是放到单片机里面数码管只闪烁一下然后熄灭
  • ¥20 系统工程中,状态空间模型中状态方程的应用。请猛男来完整讲一下下面所有问题
  • ¥15 我想在WPF的Model Code中获取ViewModel Code中的一个参数
  • ¥15 arcgis处理土地利用道路 建筑 林地分类
  • ¥20 使用visual studio 工具用C++语音,调用openslsx库读取excel文件的sheet问题
  • ¥100 寻会做云闪付tn转h5支付链接的技术
  • ¥15 DockerSwarm跨节点无法访问问题