英文:
Pointer to an empty interface type assertion
问题
我正在接收一个指向接口的指针传递给我的函数,并尝试对其进行迭代。底层类型是字符串切片,如果我使用类型interface{}
而不是指向它的指针*interface{}
,我可以将其转换为它。最佳的类型断言指针到接口的方法是什么?使用指针是因为要转换的值非常大。
以下是不起作用的代码:
func convertMember(member *interface{}) {
for _, members := range member.([]string) {
// 无效的类型断言:member.([]string)(左侧为非接口类型*interface{})
}
}
以下是带有解引用指针的不起作用的代码:
func convertMember(member *interface{}) {
for _, members := range *member.([]string) {
// 无效的类型断言:member.([]string)(左侧为非接口类型*interface{})
}
}
以下是如果我更改父函数以发送接口而不是其指针,则起作用的代码:
func convertMember(member interface{}) {
for _, members := range member.([]string) {
// 此处代码有效
}
}
或者,我应该将其类型断言为字符串切片并使用指向它的指针?
英文:
I am receiving a pointer to an interface to my function, and I am trying to iterate over it. The underlying type is a string slice, which I can convert to it if I am using type interface{}
and not a pointer to it *interface{}
What is the best way to type assert pointer to interface? Using pointer because the value to be transformed is of huge size.
Code that doesn't work:
func convertMember(member *interface{}) {
for _, members := range member.([]string) {
invalid type assertion: member.([]string) (non-interface type *interface {} on left)
Code that doesn't work with dereferencing pointer:
func convertMember(member *interface{}) {
for _, members := range *member.([]string) {
invalid type assertion: member.([]string) (non-interface type *interface {} on left)
Code that works if I change the parent function to send an interface instead of its pointer:
func convertMember(member interface{}) {
for _, members := range member.([]string) {
Or should I type assert it to string slice and use a pointer to it?
答案1
得分: 3
你需要在断言之前进行解引用:
func convertMember(member *interface{}) {
for _, members := range (*member).([]string) { ... }
}
但是为什么你想要一个指向接口的指针呢?当一个结构体实现了某个接口时,该结构体的指针也实现了该接口。所以指向接口的指针在某种程度上是不需要的。
供你参考,这里有一个相关的问题:https://stackoverflow.com/questions/13511203/why-cant-i-assign-a-struct-to-an-interface
英文:
You need to dereferencing before assertion:
func convertMember(member *interface{}) {
for _, members := range (*member).([]string) { ... }
}
But why do you want a pointer to interface? When a struct implements some interface, the pointer of that struct implements that interface too. So a pointer to interface is kind of never-need.
For your reference, here's a related question: https://stackoverflow.com/questions/13511203/why-cant-i-assign-a-struct-to-an-interface
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论