In this example, we show how to create a constructor in Golang Struct with an example.
There are no built-in constructors in Go. Programmers sometimes create constructor functions as a best practice.
Go - struct constructor example
In the example, we have the newUser constructor function, which creates new User structs. The function returns a pointer to the newly created struct.
package main
import "fmt"
type User struct {
firstName string
lastName string
email string
}
func newUser(firstName string, lastName string, email string) *User {
user := User{firstName, lastName, email}
return &user
}
func main() {
user := newUser("John", "Cena", "john@gmail.com")
fmt.Println("firstName:", user.firstName)
fmt.Println("lastName:", user.lastName)
fmt.Println("email:", user.email)
}
Output:
firstName: John lastName: Cena email: john@gmail.com
Comments
Post a Comment