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

Pointers 如何更改golang中作为结构引用传递的空接口的值?,pointers,go,struct,interface,Pointers,Go,Struct,Interface,我有许多结构作为指针传递给一个名为AutoFilled的函数。每个结构都不同于另一个结构。但有些字段是相同的,如“创建者”、“createon”、“edition”。。, 有没有办法更改自动填充函数中的公共字段 package main import ( "fmt" "time" ) type User struct { ID string Creator string CreateOn time.Time Edition int Na

我有许多结构作为指针传递给一个名为AutoFilled的函数。每个结构都不同于另一个结构。但有些字段是相同的,如“创建者”、“createon”、“edition”。。, 有没有办法更改自动填充函数中的公共字段

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")
}

看起来您只需要在其他结构中嵌入一个公共结构(有时称为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
}
此外,我还将使
自动填充
函数成为通用的方法。(使用接口会丢失类型安全性。)


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

对于每个结构(
Book
User
),创建一个名为
New的方法
func (c *Common)Autofill() {
    // set fields on Common struct
}

func main() {
        user := &User{}
        user.Autofill()

func NewBook() *Book {
    return &Book {
        //you can fill in default values here for common construct
    }
} 
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")
}