获取通过接口获取的var上的指针 [英] Get pointer on var obtained via interface

查看:78
本文介绍了获取通过接口获取的var上的指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在以下代码中

  var a intvar b接口{}b = afmt.Printf(%T,%T \ n",a,& a)fmt.Printf(%T,%T \ n",b,& b) 

输出:

  int,* intint,* interface {} 

我希望& b的类型是int的指针.

我有两个问题:

1)为什么它是接口{}上的指针?

2)如何获得原始类型的指针?

解决方案

& b =>这是地址运算符应用于类型为 interface {} 的变量 b 上.因此,& b 将是类型为 * interface {} 的指针,指向变量 b .如果您使用类型为 T 的变量的地址,则结果将始终为类型为 * T

.

您无法从 b 获取变量 a 的地址,因为赋值:

  b = a 

只需将 a 的值复制到 b 中.它将 a 的值包装在 interface {} 类型的接口值中,并将此接口值存储到 b 中.此值与 a 完全分离.

通常,所有分配复制所分配的值.Go中没有引用类型.如果首先将 a 的地址存储在 b 中,则最接近您想要的地址,例如:

  b =& a 

然后,您可以使用类型声明找出 a 来自 b 的地址,如下所示:

  fmt.Printf(%T,%T \ n",a,& a)fmt.Printf(%T,%T \ n",b,b.(* int)) 

此输出(在游乐场上尝试):

  int,* int* int,* int 

(注意:当您仅打印 b 时,由于它是接口类型,因此 fmt 包将打印包装在其中的(具体)值.)

查看相关问题:

如何获取指向被掩盖为接口的变量的指针?

更改接口下的指针类型和值反射

In the following code

var a int
var b interface{}

b = a

fmt.Printf("%T, %T \n", a, &a)
fmt.Printf("%T, %T \n", b, &b)

output:

int, *int 
int, *interface {}

I would expect the type of &b to be a pointer on int.

I have two questions:

1) Why is it a pointer on interface{} ?

2) How could I get a pointer on the original type ?

解决方案

&b => this is the address operator applied on the variable b, whose type is interface{}. So &b will be a pointer of type *interface{}, pointing to the variable b. If you take the address of a variable of type T, the result will always be of type *T.

You cannot obtain the address of the variable a from b, because the assignment:

b = a

Simply copies the value of a into b. It wraps the value of a in an interface value of type interface{}, and stores this interface value into b. This value is completely detached from a.

In general, all assignments copy the values being assigned. There are no reference types in Go. The closest you can get to what you want is if you store the address of a in b in the first place, e.g.:

b = &a

Then you can use type assertion to get out a's address from b like this:

fmt.Printf("%T, %T \n", a, &a)
fmt.Printf("%T, %T \n", b, b.(*int))

This outputs (try it on the Go Playground):

int, *int
*int, *int

(Note: when you simply print b, since it is of an interface type, the fmt package prints the (concrete) value wrapped in it.)

See related questions:

How to get a pointer to a variable that's masked as an interface?

Changing pointer type and value under interface with reflection

这篇关于获取通过接口获取的var上的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆