0

我有许多结构作为指针传递给名为 AutoFilled 的函数。每个结构都不同。但是有些字段是相同的,例如“creator”、“createon”、“edition”..,有没有办法改变 AutoFilled 函数中的公共字段?

package main

import (
    "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")
}
4

2 回答 2

3

看起来您只需要在其他结构中嵌入一个 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()

于 2020-02-10T03:14:03.613 回答
2

@AJR 提供了一个非常好的选择。这是另一种方法。

对于每个结构(BookUser),创建一个名为 的方法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")
}
于 2020-02-10T04:34:32.117 回答