为了账号安全,请及时绑定邮箱和手机立即绑定

如何更改在golang中作为结构引用传递的空接口的值?

如何更改在golang中作为结构引用传递的空接口的值?

Go
www说 2022-05-18 09:33:38
我有许多结构作为指针传递给名为 AutoFilled 的函数。每个结构都不同。但是有些字段是相同的,例如“creator”、“createon”、“edition”..,有没有办法改变 AutoFilled 函数中的公共字段?package mainimport (    "fmt"    "time")type User struct {    ID string    Creator string    CreateOn time.Time    Edition int    Name string    Password string}type Book struct {    ID string    Creator string    CreateOn time.Time    Edition int    Name string    ISBN string}func AutoFilled(v interface{}) {    // Add Creator    // Add CreateOn    // Add Edition (Version) [new is zero, edit increase 1]}func main() {    user := User{}    book := Book{}    AutoFilled(&user)    AutoFilled(&book)    fmt.Println(user)    fmt.Println(book)    fmt.Println("Thanks, playground")}
查看完整描述

2 回答

?
不负相思意

TA贡献1777条经验 获得超10个赞

看起来您只需要在其他结构中嵌入一个 Common 结构(有时称为 mixin)。


type Common struct {

    ID string

    Creator string

    CreateOn time.Time

    Edition int

}

type User struct {

    Common

    Name string

    Password string

}


type Book struct {

    Common

    Name string

    ISBN string

}

此外,我会将AutoFilled函数设为 Common 上的方法。(使用接口会失去类型安全性。)


func (c *Common)Autofill() {

    // set fields on Common struct

}


func main() {

        user := &User{}

        user.Autofill()


查看完整回答
反对 回复 2022-05-18
?
互换的青春

TA贡献1797条经验 获得超6个赞

这是另一种方法。


对于每个结构(Book和User),创建一个名为 的方法New<StructName。举Book个例子


func NewBook() *Book {

    return &Book {

        //you can fill in default values here for common construct

    }

您可以通过创建一个Common结构来进一步扩展此模式,并将该对象传递给NewBook您创建它时,即,


func NewBook(c Common) *Book {

    return &Book {

        Common: c

        //other fields here if needed

    }

}

现在在您的主代码中,您将执行此操作


func main() {

    c := NewCommon() //this method can create common object with default values or can take in values and create common object with those

    book := NewBook(c)

    //now you don't need autofill method


    fmt.Println("Thanks, playground")

}


查看完整回答
反对 回复 2022-05-18
  • 2 回答
  • 0 关注
  • 136 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号