Two Different Ways Of Creating A New Instance in GO

Example:

type MySQL struct {
    db Database
}

what is the different between

x :=MySQL{db: mysql} and

x := NewMySQL(mysql)

In Go, x := MySQL{db: mysql} and x := NewMySQL(mysql) are two different ways of creating a new instance of the MySQL struct.

The first method (x := MySQL{db: mysql}) is a struct literal syntax where we create a new instance of the MySQL struct and set its db field to the mysql object that we pass in. This method is useful when we only need to create a simple instance of a struct with a few fields.

The second method (x := NewMySQL(mysql)) involves calling a constructor function called NewMySQL that creates a new instance of the MySQL struct and sets its db field to the mysql object that we pass in. This method is useful when we need to perform more complex initialization logic, such as validating the inputs or setting default values.

type MySQL struct {
    db Database
}

func NewMySQL(db Database) *MySQL {
    return &MySQL{db: db}
}

In this example, the NewMySQL function takes a Database object as its input and returns a pointer to a new instance of the MySQL struct with its db field set to the Database object that we passed in.

Using the NewMySQL constructor function allows us to encapsulate the logic of creating a new instance of the MySQL struct and setting its fields, which can make our code more modular and easier to maintain.

Leave a Reply

Your email address will not be published. Required fields are marked *

27 + = 34

Related Post