1

I have many struct that pass as pointer to a function called AutoFilled. each struct is different from another. but some field are the same such as "creator", "createon", "edition".., Is there any way to change common field in AutoFilled function?

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

2 Answers 2

3

It looks like you just need a Common struct embedded (sometimes called mixin) in the other structs.

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
}

Also I would make the AutoFilled function a method on Common. (Using an interface you lose type safety.)

func (c *Common)Autofill() {
    // set fields on Common struct
}

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

Sign up to request clarification or add additional context in comments.

Comments

2

@AJR has given a very good option. here is an alternative approach.

For each struct (Book and User), create a method called New<StructName. Taking Book as an example

func NewBook() *Book {
    return &Book {
        //you can fill in default values here for common construct
    }
} 

You can further extend this pattern by creating a Common struct and pass in that object to NewBook when you are creating it i.e.,

func NewBook(c Common) *Book {
    return &Book {
        Common: c
        //other fields here if needed
    }
}

Now in your main code, you will do this

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.