dongyu1979 2018-09-20 03:16
浏览 30
已采纳

如何在未知类型的结构中修改字段?

I have multiple structs that have one common field; let's call it common here

type Struct1 struct {
    foo string
    bar string

    common string
}

type Struct2 struct {
    baz int
    qux string

    common string
}

I want to create a function that takes an Interface as input and nullifies common. The available struct types won't be known at compile time, so I can't create a separate function for each type, and I can't use a switch statement.

P.S: In my use-case, I want to nullify common because it holds the creation time of each struct, and I want to track the history of the struct, so I will know if it changes. Having the creation time inside the struct will mess this up because the creation time will be different every time a new struct is generated even though its actual data may be the same.

  • 写回答

1条回答 默认 最新

  • douxiong5438 2018-09-20 03:38
    关注

    Define a struct with the common fields and make it implement an interface which says that it is able to nullify the common fields. Then embed this struct into your other struct types that should be able to nullify the fields.

    // CommonNullifier is able to nullify its common field(s)
    type CommonNullifier interface {
            NullifyCommon()
    }
    
    // StructCommon contains the common struct fields
    type StructCommon struct {
            Common string
    }
    
    func (sc *StructCommon) NullifyCommon() {
            sc.Common = ""
    }
    
    // Struct1 embeds common fields, thus implements CommonNullifier
    type Struct1 struct {
            StructCommon
            Foo string
    }
    
    // Struct2 also embeds common fields, thus also implements CommonNullifier
    type Struct2 struct {
            StructCommon
            Bar string
    }
    
    // NullifyCommon nullfies the 'common' fields in the argument
    func NullifyCommon(s CommonNullifier) {
            s.NullifyCommon()
    }
    

    (See it on the Go Playground)

    You could also use reflection, but using an interface is generally more readable.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 opencv 无法读取视频
  • ¥15 用matlab 实现通信仿真
  • ¥15 按键修改电子时钟,C51单片机
  • ¥60 Java中实现如何实现张量类,并用于图像处理(不运用其他科学计算库和图像处理库))
  • ¥20 5037端口被adb自己占了
  • ¥15 python:excel数据写入多个对应word文档
  • ¥60 全一数分解素因子和素数循环节位数
  • ¥15 ffmpeg如何安装到虚拟环境
  • ¥188 寻找能做王者评分提取的
  • ¥15 matlab用simulink求解一个二阶微分方程,要求截图