
Description
What version of Go are you using (go version
)?
1.8
What operating system and processor architecture are you using (go env
)?
darwin/amd64
What did you do?
In my project, we generate C++/python APIs from certain schema that model network configuration and operational data. We guarantee that each node in the data model has a corresponding type in the C++/python APIs. For example, APIs for python can be seen here.
So, if the data model looks like the below,
container employee {
leaf employee-id {
type string;
}
container employment-data { // data model is nested
leaf date-of-joining {
type string;
}
}
}
the corresponding python classes look like:
class Employee(object):
def __init__(self):
self.employee_id = None
self.employment_data = EmploymentData()
class EmploymentData(object): #type is nested
def __init__(self):
self.date_of_joining = None
Some of the data model schema happen to be deeply nested, which can be nicely represented as nested classes (aka inner classes) in C++/python. When it comes to generating code for Go, however, there is no way to have named nested types. The only approach is to have named types which are defined in a flat way and then the fields themselves can be nested. So, we are being forced to have long struct names due to concatenating the names of the "inner" types to guarantee unique names for all the types in a package.
type Employee struct {
employee_id string
employment_data EmployeeEmploymentData // data is nested
}
type EmployeeEmploymentData struct { // type is flat (not nested)
date_of_joining string
}
The alternative would be to use nested anonymous structs, but it is a bit cumbersome for users to initialize such structs.
Can Go allow named nested structs like the below?
type Employee struct {
EmployeeId string
EmploymentData type EmploymentData struct { // type is named and nested
DateOfJoining string
}
}
Note that even C lets you have named inner types (although they are not of much practical use):
struct Employee {
char* employee_id;
struct EmploymentData { // type is named and nested
char* date_of_joining;
} employment_data'
}
However, in Go, it could perhaps let users initialize their objects like the below (EmploymentData
only has scope as a nested type of Employee
)
bob := Employee{EmployeeId:"1234", EmploymentData{DateOfJoining: "12-12-2010"}}
As a consequence, the below could also be valid for declaring orphan objects of the above nested type
data := Employee.EmploymentData{DateOfJoining: "12-12-2010"}