I have a scenario where I have two structs and I know I can nest them as below
type student struct {
id int
name string
branch string
contact string
}
type book struct {
id int
name string
author string
release time.Time
}
type libraryNested struct {
member student
rented book
}
but what if in the nested struct I am not interested in all the struct fields from its parent struct.
is there any way I can just get a subset of struct fields from the parent and then have it under the libraryNested struct.
The fields that are of interest to me is as below, but I don’t want to declare what I already have declared just for the sake of having a new struct that holds my data.
type libraryWithoutNest struct {
studentid int
studentName string
bookid int
bookName string
}
I would also like to know if it is a good practice to do this.
to give you a bit of context I actually do have two tables and they are related with an id and I am coming up with an inner join query to connect both them.
The structs student and library are my models and now I am doing a query that relates both the table and I am in need of only a subset of what student model and book model has to offer as fields… So what is the best approach to bind a struct to the resulting value that I get from a the inner join query.
If you need a type with only some fields, you will have to define it. Type composition will result in a type having all fields of the embedded types, as you have observed.
Yes, this is duplication. No, I know if no way to avoid it.