Subset of struct fields as a nested resulting struct

Hi All,

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.

Your libraryNested struct is a composition of a full student and book, it has a student and it has a book. Is this really what you want to model here?

Maybe libraryNested is better called studentBookRental, a struct that refers to a student and a book.

type studentBookRental struct {
    studentId int
    bookId    int
}

Think a join table in a relational database.

Hey @lutzhorn, Thanks for your response…

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.

Thanks @lutzhorn

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