Struct Constructor

Hi,

I used a constructor Make pattern for struct in that way:

package main

import (
	"fmt"
)

type Etc struct {
	Foo string
	Bar int
}
	
func (Etc) Make(foo string, bar int) Etc {
	return Etc{
		Foo: foo,
		Bar: bar,
	}
}

func main() {
	fmt.Printf("%#+v\n", Etc.Make(Etc{}, "foo_string", 0xbeef))
}

Is that correct to use this kind of constructors with an extra-parameter (actual “receiver” as far as I understand)?

I like to follow the community code examples.

I never saw that kind of code. I usually see :

func MakeEtc(foo string, bar int) Etc {
...
}

//or something like this
func MakeEtc(foo string, bar int, etc *Etc) {
...
}

Thanks,

BTW, as I understand golang naming rules, New functions should return pointer and Make functions should return value. Is it right?

Correct!!

Here is an example of how I write a constructor. This is a sample for a microservices app. I prefix my constructors with “New”

//Each Aggregate in a microservices application has
//it's own repository.
package main

import "fmt"

type CustomerRepository interface {
    Add()
}

type CustomersRepository struct {
   DatabaseName   string
   CollectionName string
}

func main(){
   n := NewCustomersRepository("testDB", "testCollection")
   fmt.Printf("Created new CustomersRepository instance %T\n %s %s \n", n, 
   n.DatabaseName, n.CollectionName)
}

func NewCustomersRepository(database string, collection string) *CustomersRepository {
   return &CustomersRepository {
    DatabaseName: database,
    CollectionName: collection,
   }  
}
1 Like

Hi,

No, it’s not correct. You create a struct function then you call it by referencing through the struct itself and pass it a Etc object to fulfill the receiver parameter !! Why would you pass a Etc object to generate one without using it ?
The correct way would be :

package main

import (
   "fmt"
)

type Etc struct {
   Foo string
   Bar int
}

func Make(foo string, bar int) Etc {
   return Etc{
  	  Foo: foo,
	  Bar: bar,
   }
}
func main() {
    fmt.Printf("%#+v\n", Make("foo_string", 0xbeef))
}

Have a nice day.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.