go - 由于指针接收器无法实现 Go 接口(interface)

标签 go

我的去测试无法通过。怎么了? (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)
}

当我运行 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]

最佳答案

1- 你可以使用

server := &EchoServer{}

代替

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.

并查看:Pointer receiver and Value receiver difference in implementation with Iris framework


2- 或者你可以使用

func (server EchoServer) Name() string {
    return "EchoServer"
}

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

server := EchoServer{}

关于go - 由于指针接收器无法实现 Go 接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39813730/

相关文章:

string - Golang 不转义字符串变量

go - 如何等待 panic 的协程?

字符串错误 : unknown escape sequence:/

go - goroutine 没有输出

heroku - 如何在 Heroku 上使用我的 Go 网络应用程序构建实用程序?

go - 时间戳中的 "m"是什么以及如何在没有 "m"的情况下获取时间戳?

Go 中的 JSON 解析 - 技巧

go - 为什么他们不同

multithreading - Go 服务器在发送 INT 信号后挂起

go - CloudFlare 不会让我只提供 HTTPS,它只有在我同时提供 HTTP 和 HTTPS 时才有效