Constructors in Golang
There are no default constructors in Go, but you can declare methods for any type. You could make it a habit to declare a method called "Init". Not sure if how this relates to best practices, but it helps keep names short without loosing clarity.
Example
package main
import "fmt"
type Employee struct {
Name string
Age int
}
func (e *Employee) Init(name string, age int) {
e.Name = name
e.Age = age
}
func info(name string, age int) *Employee {
e := new(Employee)
e.Name = name
e.Age = age
return e
}
func main() {
emp := new(Employee)
emp.Init("John Doe",25)
fmt.Printf("%s: %d\n", emp.Name, emp.Age)
empInfo := info("John Doe",25)
fmt.Printf("%v",empInfo)
}
Output
John Doe: 25
&{John Doe 25}
Most Helpful This Week
How to check if a string contains a substring in Golang?
How to set, get, and list environment variables?
How to print struct variables data in Golang?
How to Convert string to integer type in Go?
Get Hours, Days, Minutes and Seconds difference between two dates [Future and Past]
Example: Stack and Caller from RUNTIME package
How to split a string on white-space?
Replace any non-alphanumeric character sequences with a dash using Regex
Get Year, Month, Day, Hour, Min and Second from a specified date
How to remove symbols from a string in Golang?