golang

Golang Constructor Like Functions

Go is not an objected-oriented programming language, at least not in the traditional OOP patterns. It borrows some features and provides instances that come cross to OOP. Although this can be a daunting migration, especially for developer from OOP languages, it makes up for it with its simplicity.

In this article, we will discuss how to create a constructor in Go using native functions.

Constructor Like Functions

Let us define a simple struct as shown in the code below:

type User struct {
    Name   string
    Age    int
    Salary float64
}

From the struct, we can create a function like constructor as shown in the example:

func user_info(name string, age int, salary float64) *User {
    u := new(User)
    u.Name = name
    u.Age = age
    u.Salary = salary
    return u
}

The above will create a constructor-like function from the User type. If we check the type, we should get:

fmt.Println(reflect.TypeOf(user_info("Jonathan Archer", 45, 140000.33)))
*main.User

As you see the way to create constructors in Go is to create functions that return an oobject pointer.

An example function is as show:

func (u *User) Init(name string, age int, salary float64) {
    u.Name = name
    u.Age = age
    u.Salary = salary
}

We can use the function as:

user := new(User)
user.Init("Jonathan Archer", 45, 140000.33)
fmt.Printf("%s: %d: %f\n", user.Name, user.Age, user.Salary)

Conclusion

In this article, we explored how to introduce OOP in Go using structures and functions that return a pointer.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list