Golang. A simple concept of a constructor

In Go it does not exist the concept of a constructor like in other languages. A struct is a very flexible construct that can be defined in many ways. When working with structs it is very important to take into consideration fields zero values and how these values may impact the code. In many cases, it is a good practice to define constructors, especially when certain values are not valid.

package main

type Box struct {
	Height int
	Width  int
}

// It's a kind of constructor
func NewBox(height int, width int) (*Box, error) {
	if height <= 0 || width <= 0 {
		return nil, errors.New("params must be greater than zero")
	}

	return &Box{height, width}, nil
}

func main() {
	b, err := NewBox(1, 2)
	if err != nil {
		...
	}
}