drudfe0446838 2018-11-01 02:07 采纳率: 0%
浏览 2

是否可以更改存储在空接口中的结构的成员

I have this:

type pair struct {
    a, b int
}

Then I define two variables:

x := pair{ 3, 4 }
var y interface{} = x

I realize that y doesn't store a reference of x but a copy of it via the following code:

x.b = 7
fmt.Println(x)
fmt.Println(y)
// got:
// {3 7}
// {3 4}

Also see: https://github.com/golang/go/blob/master/src/runtime/iface.go#L359

Is there any way to modify pair.y member of the copied struct in y?

Tried this: (fail)

// cannot assign to y.(pair).b
y.(pair).b = 7

Tried this: (also fail)

// panic: reflect: reflect.Value.SetInt using value obtained using unexported field
v := reflect.ValueOf(y).FieldByName("b")
v.SetInt(33)

Change "b" to "B": (also fail)

type pair {
    a, B int
}
// panic: reflect: reflect.Value.SetInt using unaddressable value
v := reflect.ValueOf(y).FieldByName("B")
v.SetInt(33)

Update:

I'm not going to change x.b using y. I want to change y's field b alone.

Thanks for your help, but this is not a simple question about values and references.

  • 写回答

2条回答 默认 最新

  • dongweihuai5601 2018-11-01 05:18
    关注

    You need to know the pointer and address first.Use the pointer can change the value deeply.If you want y to have the same value as x, they need to point to the same address.

    评论

报告相同问题?

悬赏问题

  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥100 已有python代码,要求做成可执行程序,程序设计内容不多
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助
  • ¥15 STM32控制MAX7219问题求解答
  • ¥20 在本地部署CHATRWKV时遇到了AttributeError: 'str' object has no attribute 'requires_grad'