Abstract & Codes
I'm learning Golang and Nim which don't have class
but has struct
, and new to these kind of language. Being used to OOP I tried to make a class-like thing using struct but found that struct's fields are optional. I want to turn them mandatory in order to write strict code.
JAVA
class Person {
String Name
int Age
Person(String Name, int Age) {
this.Name = Name;
this.Age = Age;
}
}
// Ok
Person p1 = new Person("John Doe", 30);
// FAILS
Person p2 = new Person("John Doe");
Golang
type Person struct {
Name string
Age int
}
// Ok
p1 := Person{
Name: "John Doe",
Age: 30,
}
// Ok
p2 := Person{
Name: "John Doe",
}
One of the solution is to implement a function that initializes struct; if arguments are not entirely passed it fails.
Golang
func newPerson(Name string, Age int) Person {
return Person{
Name: Name,
Age: Age,
}
}
// Ok
p1 := newPerson("John Doe", 30)
// FAILS
p2 := newPerson("John Doe")
Question
I feel the above solution redundant because init function has to come along with each struct. Is this method popular or there's better solution?