dongweicha6077 2017-01-09 04:27
浏览 115
已采纳

如果参数的类型是interface {},那么如何知道是通过指针传递还是通过值传递?

Given any function that takes a parameter of type interface{} how would I know whether or not to pass that parameter with or without & without navigating the source code of the function.

For example if I had a function with this type signature given to me:

func foo(x interface{}, y int) int

Would there be any way to figure out if x was supposed to be passed by value or by pointer?

  • 写回答

2条回答 默认 最新

  • douyue2313 2017-01-09 04:44
    关注

    Here is the snippet from the source:

    // DecodeElement works like Unmarshal except that it takes
    // a pointer to the start XML element to decode into v.
    // It is useful when a client reads some raw XML tokens itself
    // but also wants to defer to Unmarshal for some elements.
    
    func (d *Decoder) DecodeElement(v interface{}, start *StartElement) error {
        val := reflect.ValueOf(v)
        if val.Kind() != reflect.Ptr {
            return errors.New("non-pointer passed to Unmarshal")
        }
        return d.unmarshal(val.Elem(), start)
    }
    

    It is checking val.Kind() != reflect.Ptr Which means you have to pass the pointer i.e &v.

    Its entirely depend on the person who wrote the method or function, so interface{} could be either *ptr or anything but u ve to check that inside your function using reflect.ValueOf(v).Kind() whether the value is a pointer or not and proceeds accordingly.

    And little bit about empty interface:

    The interface type that specifies zero methods is known as the empty interface:

    interface{}

    An empty interface may hold values of any type. (Every type implements at least zero methods.)

    Empty interfaces are used by code that handles values of unknown type. For example, fmt.Print takes any number of arguments of type interface{}.

    Another useful discussion: docs

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥30 seata使用出现报错,其他服务找不到seata
  • ¥35 引用csv数据文件(4列1800行),通过高斯-赛德尔法拟合曲线,在选取(每五十点取1点)数据,求该数据点的曲率中心。
  • ¥20 程序只发送0X01,串口助手显示不正确,配置看了没有问题115200-8-1-no,如何解决?
  • ¥15 Google speech command 数据集获取
  • ¥15 vue3+element-plus页面崩溃
  • ¥15 像这种代码要怎么跑起来?
  • ¥15 安卓C读取/dev/fastpipe屏幕像素数据
  • ¥15 pyqt5tools安装失败
  • ¥15 mmdetection
  • ¥15 nginx代理报502的错误