如何强制编译器控制值/指向值的函数参数?

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

How to force compiler to control value/pointer-to-value func arguments?

问题

处理go的函数时,我发现当使用'generic' interface{}类型时,无法强制编译器控制我是传递值还是指向值的指针参数。

func f(o interface{}) {
...
}

最明显的解决方案是使用以下修改:

func f(o *interface{}) {
...
}

尽管这样可以成功编译,但我认为这一步不正确。那么,有没有办法表明我想传递任何指针

英文:

Dealing with go's funcs I discovered that one can't force the compiler to control whether I pass a value or pointer-to-value argument when using 'generic' interface{} type.

func f(o interface{}) {
...
}

The most obvious solution is to use the following modification:

func f(o *interface{}) {
...
}

Although this is successfully compiled I didn't find this step right. So, is there any means to state that I want to pass any pointer?

答案1

得分: 2

你需要使用反射

import "reflect"

func f(o interface{}) {
  if _, ok := reflect.TypeOf(o).(*reflect.PtrType); !ok {
    panic("不是指针")
  }
  // ...
}

你也可以考虑使用unsafe.Pointer,但类型信息会丢失。

英文:

You'd have to use reflection.

import "reflect"

func f(o interface{}) {
  if _, ok := reflect.Typeof(o).(*reflect.PtrType); !ok {
    panic("Not a pointer")
  }
  // ...
}

You could also consider unsafe.Pointer, but the type information would be lost.

答案2

得分: 1

在编译时,interface{},即空接口,可以表示任何类型。

> 所有类型都实现了空接口:interface{} 接口类型

英文:

No. At compile time, interface{}, the empty interface, is any type.

> all types implement the empty
> interface: interface{} Interface
> types

huangapple
  • 本文由 发表于 2010年9月28日 06:43:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/3808454.html
匿名

发表评论

匿名网友

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

确定