指向空接口类型断言

huangapple go评论89阅读模式
英文:

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

huangapple
  • 本文由 发表于 2016年4月11日 22:05:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/36551041.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定