baixeing
(baixeing)
November 26, 2018, 11:39am
1
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)?
heatbr
(Onezino Moreira)
November 26, 2018, 12:24pm
2
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) {
...
}
baixeing
(baixeing)
November 26, 2018, 1:23pm
3
Thanks,
BTW, as I understand golang naming rules, New
functions should return pointer and Make
functions should return value. Is it right?
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
imatmati
(Ivan Matmati)
November 28, 2018, 9:44am
6
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.
system
(system)
Closed
February 26, 2019, 9:44am
7
This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.