假设我有一个将客户端ID映射到net.Conns(接口)的存储。为了简单起见,它只是将 map 隐藏在其中,并获取 map 关键字作为参数。

我想消除对值复制的需求,并且我来自Java领域,因此该映射应该将id映射到net.Conn指针似乎是合乎逻辑的。

type Storage struct {
     conns map[int]*net.Conn
}

func (s *Storage) Add(id int, conn *net.Conn){
   s.conns[id] = conn
}

... methods for initialising new storage, getting, deleting,
maybe giving list of user id's etc.

现在,我想为代码编写自动测试,但没有实际的Conns,因此我编写了自己的StubbConn和Stubb所有net.Conn -interface方法。
type StubConn struct{}

func (s *StubConn) Read(b []byte) (n int, err error)   { return 0, nil }
func (s *StubConn) Write(b []byte) (n int, err error)  { return 0, nil }
etc..

然后我尝试在测试中使用此StubbConn ...
func TestAddOneClient(t *testing.T) {
    clients := GetStorage()
    conn := new(StubConn)
    clients.Add(5, conn)
    if len(clients.conns) != 1 {
        t.Error("Expected client adding to increment storage map size")
    }
}

它导致编译错误:
cannot use conn (type *StubConn) as type *net.Conn in argument to clients.Add:
*net.Conn is pointer to interface, not interface

但是,如果add函数将参数作为conn net.Conn(值)并改为使 map 保留值,则该方法有效。因此,即使Stubb接口似乎也不会将Stubb指针作为指向真实接口的指针传递。

有没有办法将我的StubbConn指针作为指向Conn的指针传递给将接口指针作为参数的函数?

即使我完全迷路了,应该让我的 map 有机会持有实际的Conn值而不是指针(并且请告诉我是否应该这样做),对于单元测试其他将指向接口的指针作为参数的函数的问题仍然存在。

最佳答案

net.Conn 是一个接口。几乎永远不需要使用指向接口的指针,并且您也不会找到任何采用指向接口的指针的函数。

在 map 中使用net.Conn值。

conns map[int]net.Conn

10-06 12:44
查看更多