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 前端页面想做个定时任务,但是使用requestAnimationFrame,setinterval和settimeout都不行
  • ¥15 根据以下文字信息,做EA模型图
  • ¥15 删除虚拟显示器驱动 删除所有 Xorg 配置文件 删除显示器缓存文件 重启系统 可是依旧无法退出虚拟显示器
  • ¥15 vscode程序一直报同样的错,如何解决?
  • ¥15 关于使用unity中遇到的问题
  • ¥15 开放世界如何写线性关卡的用例(类似原神)
  • ¥15 关于并联谐振电磁感应加热
  • ¥60 请查询全国几个煤炭大省近十年的煤炭铁路及公路的货物周转量
  • ¥15 请帮我看看我这道c语言题到底漏了哪种情况吧!
  • ¥60 关机时蓝屏并显示KMODE_EXCEPTION_NOT_HANDLED,怎么修?