If you are searching many times, create a fast data structure, such as a map[customer][]order. If you are doing it just once, then search linearly through the orders slice.
Student_code int `db:"student_code"`
Subjectname string `db:"subjectname"`
Marks int `db:"marks"`
}
type Students struct {
Student_code int db:"student_code"
Batch_division string db:"batch_division"
Rollno int db:"rollno"
Name string db:"fullname"
Marks []SudentsMarks
}
var err error
var _students = []Students{}
var _studentsMarks = []SudentsMarks{}
studentquery := select * from students
marksquery := select * from marks
If you create a mapping from student code to Students, then you don’t have to do an O(n^2) nested loop. The following is O(n). I don’t know why you create a new SudentsMarks in the inner loop instead of reusing the one in the slice.
studentsByCode := make(map[int]*Students)
for i := range _students {
studentsByCode[s[i].Student_code] = &s[i]
}
for _, m := range _studentsMarks {
s,ok := studentsByCode[m.student_code]
if ok {
s.Marks = append(s.Marks, m)
} else {
panic("missing student for marks")
}
}
In your approach . I have to transfer my struct data into map .
using following code according to you.
studentsByCode := make(map[int]*Students)
for i := range _students {
studentsByCode[s[i].Student_code] = &s[i]
}
The map holds a pointer to each struct, so there’s minimal extra memory required and no copying. In terms of space-time tradeoff, there can be a lot of time saved for just a little bit of extra space.