gpt4 book ai didi

pointers - 指针的 slice ,当传递给对象时,得到具有其他地址的指针

转载 作者:IT王子 更新时间:2023-10-29 02:22:22 26 4
gpt4 key购买 nike

我正在尝试将一部分指针传递给实现接口(interface) LogicAdapter 的结构。这是我的代码:

ma​​in.go:

var adapters[]LogicAdapter
adapter1 := &ExampleAdapter{}
fmt.Printf("Addr: %p\n", adapter1)
adapters = append(adapters, adapter1)
bot := ChatterBot{"Charlie", MultiLogicAdapter{adapters}}
bot.getResponse("test", 0)

多适配器逻辑.go:

type MultiLogicAdapter struct {
adapters []LogicAdapter
}

func (logic *MultiLogicAdapter) process(text string, session int) string {
//response := logic.adapters[0].process(text, session)
response := ""
for _, adapter := range logic.adapters {
fmt.Printf("Addr: %p\n", &adapter)
}
_ = response
return ""
}

main 的输出是:

Addr: 0x5178f0

Addr: 0xc42000a340

我没有包括 LogicAdapter,因为我认为它没有必要。我不喜欢用太多代码来填充它,但这里是 ChatterBot,如果它能让事情更容易理解(但请记住 bot.getResponse 调用 process,仅此而已)

chatterbot.go

type ChatterBot struct {
Name string
MultiLogicAdapter
}

func (bot *ChatterBot) getResponse(text string, session int) string {
response := bot.process(text, session)
_ = response
return ""
}

首先,我想到了以这种方式存储指向 LogicAdapter 的指针

var adapters[]*LogicAdapter

但每次我尝试在此处插入 adapter1 指针时,我都会得到:

*LogicAdapter是指向接口(interface)的指针,不是接口(interface)

所以我发现了this并了解到:

When you have a struct implementing an interface, a pointer to that struct implements automatically that interface too. That's why you never have *SomeInterface in the prototype of functions, as this wouldn't add anything to SomeInterface, and you don't need such a type in variable declaration (see this related question).

所以我决定保留 adapters[] 声明,如您在代码中所见。问题在于,除了 adapters 存储指向 adapter1 的指针外,当它在 MultiLogicAdapter 中打印时,它是另一个地址。我知道我将 adapters 作为副本传递给 MultiLogicAdapter,但该副本将具有对 adapter1 的相同引用。那么发生了什么?

为什么我要遍历指针?因为这个:https://www.goinggo.net/2013/09/iterating-over-slices-in-go.html如果我不这样做,我将创建很多不必要的副本。

最佳答案

var adapters []LogicAdapter 中,您有一个接口(interface)数组。接口(interface)本身本质上是一个对象,带有指向您分配给它的对象的指针(带有一些额外信息来跟踪其类型等)。因此,当您向其附加一个 *ExampleAdapter 时,您将创建一个接口(interface)实例,其中包含一个指向 ExampleAdapter 的指针。

稍后,当您执行 for _, adapter := range logic.adapters {...} 时,循环中声明的变量 adapter 将是 slice 中的接口(interface)“对象”。因此,当您使用 &adapter 获取指向它的指针时,您会得到一个指向 interface 的指针,而不是指向接口(interface)包含指向的 ExampleAdapter 的指针。

有关接口(interface)内部结构的更详细说明,请参见示例 https://research.swtch.com/interfaces .

关于pointers - 指针的 slice ,当传递给对象时,得到具有其他地址的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42049875/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com