golang中两个map[uint64]interface会互相影响吗
import (
"fmt"
"testing"
)
type InterfaceConnection interface {
DoSomething() int
}
type MyConnection struct {
id int
}
func (c *MyConnection) DoSomething() int {
fmt.Println("Doing something:", c.id)
return c.id
}
func Test2(t *testing.T) {
Connections := make(map[uint64]InterfaceConnection)
_workerConnections := make(map[uint64]InterfaceConnection)
conn := &MyConnection{id: 1}
Connections[1] = conn
_workerConnections[1] = conn
fmt.Printf("%p", Connections[1])
fmt.Println()
delete(Connections, 1)
// 此时 _workerConnections 也被修改了,对应条目被删除
fmt.Printf("%p", _workerConnections[1])
}
//结果
//0xc0003fd550
//0xc0003fd550
gpt3.5回答1:
如果 _workerConnections 和 Connections 的 InterfaceConnection 类型的值都是通过同一个接口变量赋值得到的,那么它们引用的是同一个底层对象。在这种情况下,删除 Connections 中的条目会同时对 _workerConnections 产生影响。
因为它们引用同一个底层对象,当你删除 Connections 中的某个条目时,底层对象也会被修改,从而影响到 _workerConnections 中相应的条目。
我纠正:
不对。如果真的产生影响,那么,fmt.Printf("%p", _workerConnections[1])应该是nil, 现在他们都能输出0xc0003fd570
gpt3.5回答2:
非常抱歉,我在之前的回答中犯了个错误。我混淆了指针和接口类型的概念。当引用同一个底层对象时,删除 Connections 中的条目不会直接影响 _workerConnections。
在你的代码中,Connections 和 _workerConnections 都是 map[uint64]workerman_go.InterfaceConnection 类型的映射,但它们是两个不同的变量,分别引用独立的映射。删除 Connections 中的条目不会自动删除 _workerConnections 中的对应条目。