douwan2664 2019-02-08 12:49
浏览 39
已采纳

获取通过接口获取的var上的指针

In the following code

var a int
var b interface{}

b = a

fmt.Printf("%T, %T 
", a, &a)
fmt.Printf("%T, %T 
", 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 ?

  • 写回答

2条回答 默认 最新

  • duandang9434 2019-02-08 12:52
    关注

    &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 
    ", a, &a)
    fmt.Printf("%T, %T 
    ", 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

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

报告相同问题?

悬赏问题

  • ¥60 pb数据库修改或者求完整pb库存系统,需为pb自带数据库
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路