英文:
Trying to dereference an interface that is a pointer to a struct object on the back end so I can pass by value to a function
问题
我有一个表示指向已初始化的结构体对象的接口。我想要访问接口引用的对象的值,而不是指针,这样我就可以将其作为接口类型按值传递给函数。
这是我的问题的示例:https://play.golang.org/p/_3vKThlj-V
我希望能够将val按值传递给我的主函数中的EvalTest函数,这样我就可以在另一个线程中覆盖TestStruct对象的指针,而不会导致另一个线程中的指针解引用问题。
问题是,我正在针对接口对象运行数千个goroutine,但每50个goroutine调用后,我必须重新初始化指针,这是由于我正在集成的系统的限制。这似乎导致了一个不一致的状态,新的结构体初始化尚未完全完成时,goroutine尝试再次访问它。因此,我希望按值传递它,这样我就不必担心指针被替换。
对此有什么想法吗?
英文:
I have an interface that represents a pointer to a struct object after it has been initialized. I want to get access to the Value of the object that the interface references rather than the pointer so that I can pass it by value to a function as the interface type.
Here is an example of my issue: https://play.golang.org/p/_3vKThlj-V
I want to be able to pass val by value to the function EvalTest in my main function so that I can overwrite the pointer to the TestStruct object in another thread without causing pointer dereference issues in another thread.
The problem is that I'm running several thousand go routines against my interface object, but every 50 go routine calls I have to re-initialize my pointer due to a constraint of the system I'm integrating with. This seems to be leading to an inconsistent state where the new struct initialization is not completely finished when the go routines attempt to access it again. So the reason I wanted to pass it by value was so that I don't have to worry about the pointer being swapped out.
Any thoughts on this?
答案1
得分: 0
这个问题通过利用一个通道来进行我的集成 API 连接,并在成功初始化时传递一个新的指针来解决。我还使用了一些其他的优化方法,以确保只在成功连接时替换指针。以下是我从 Go Slack 频道的 Paul K 那里得到的一个示例链接:
https://play.golang.org/p/AmbsfQOzol
英文:
This was solved by utilizing a channel for my integration api connection and passing a new pointer down the channel whenever it was successfully initialized. There were also some other optimizations that I was able to use to ensure that I was only replacing the pointer in the event of a successful connection. Here is an example of what I used that I got from Paul K in the Go slack channel.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论