dongxing1965 2015-04-17 08:39
浏览 40

避免Go复制界面数据

This is part of real world code I'm trying to write. The problem is that Go copies the interface sibling so I can't modify the data. However, if I change to using a pointer to an interface then the concept of equality fails. I know I can use DeapEquals, but not in a map.

package main

import (
    "fmt"
)

type Q interface {
    modify()
}

type P struct {
    name    string
    sibling Q
}

func (x P) modify() {
    x.name = "a"
}

func main() {
    a := P{"a", nil}
    A := P{"?", nil}

    b := P{"b", a}
    B := P{"b", A}

    B.sibling.modify()

    fmt.Println(B)
    fmt.Println(b == B)
}

How do I get Go to let me modify the interface data itself without copying it and modifying the copy?

It seems these are mutually exclusive on a struct:

  • I need to be able to use maps
  • I need to be able to modify the interface data with methods
  • 写回答

2条回答 默认 最新

  • douqi3913 2015-04-17 09:18
    关注

    The only way to modify the data without copying it is to use pointers.

    I'm a little confused by what you are saying as your example uses a struct and you talk about structs but then you say you need to be able to use maps. Either way, DeepReflect works with both. Here is your example modified to use pointers:

    package main
    
    import (
        "fmt"
        "reflect"
    )
    
    type Q interface {
        modify()
    }
    
    type P struct {
        name    string
        sibling Q
    }
    
    func (x *P) modify() {
        x.name = "a"
    }
    
    func main() {
        a := P{"a", nil}
        A := P{"?", nil}
    
        b := P{"b", &a}
        B := P{"b", &A}
    
        B.sibling.modify()
    
        fmt.Println("a:", a)
        fmt.Println("A:", A)
        fmt.Println("b:", b)
        fmt.Println("B:", B)
        fmt.Println(b == B)
        fmt.Println(reflect.DeepEqual(b, B))
    }
    

    Prints:

    a: {a <nil>}
    A: {a <nil>}
    b: {b 0x10436180}
    B: {b 0x10436190}
    false
    true
    

    And you can see this post for doing the same with maps.

    评论

报告相同问题?

悬赏问题

  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 正弦信号发生器串并联电路电阻无法保持同步怎么办
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 个人网站被恶意大量访问,怎么办
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)