Reputation: 63
I have struct for order list. I want order map
and find it way. But i don't want create this for all types, that i have. Maybe I need another code? Or how I can rewrite it for universal, that I can use it with all types, that have Prev
and Next
.
type Post struct { //for example
P string
O int
Prev, Next *Post
}
type Act struct {
I int
Prev, Next *Act
}
type Map struct {
Act map[int]*Act
First, Last *Act
}
func (m *Map) New(a *Act) int {
Ida++
f := Ida
a.Id = Ida
m.Act[Ida] = a
if m.First == nil {
m.First = a
} else {
m.Last.Next = a
a.Prev = m.Last
}
m.Last = a
return f
}
func (m *Map) Del(s int) {
if _, ok := m.Act[s]; ok {
if m.Last == m.First {
m.Last = nil
m.First = nil
delete(m.Act, s)
return
}
if m.Last == m.Act[s] {
m.Last = m.Act[s].Prev
m.Act[s].Prev.Next = nil
delete(m.Act, s)
return
}
if m.First == m.Act[s] {
m.First = m.Act[s].Next
m.Act[s].Next.Prev = nil
delete(m.Act, s)
return
}
m.Act[s].Prev.Next = m.Act[s].Next
m.Act[s].Next.Prev = m.Act[s].Prev
delete(m.Act, s)
return
}
}
Upvotes: 1
Views: 591
Reputation: 31109
If to define Next
and Prev
operations as methods:
type Act struct {
I int
Prev, Next *Act
}
func (a *Act) GetNext(){
return a.Next
}
you could have an interface:
type PrevNext interface {
GetNext() *Act
GetPrev() *Act
// ... and all other required actions
}
So you could define Del()
not as method but as generic function which expects object of PrevNext
type with all required operations defined as methods.
func Del(m *PrevNext, s int) {
if _, ok := m.Act[s]; ok {
if m.GetLast() == m.GetFirst() {
m.SetLast(nil)
m.SetFirst(nil)
delete(m.Act, s)
return
}
// ....
}
}
Upvotes: 1
Reputation: 8490
You can define function which would work with all types that implements Prev()
and Next()
methods. For example something like this
type List interface{
Next() List
Prev() List
First() List
Last() List
Value() interface{}
SetNext(List)
SetPrev(List)
}
func Del(l List, elem_to_delete interface{}){
for e:=l.First(); e != l.Last(); e = l.Next()
if l.Value() == elem_to_delete{
l.Prev().SetNext(l.Next())
l.Next().SetPrev(l.Prev())
break
}
}
}
//and implement those methods for your types
type Post struct { //for example
P string
O int
Prev, Next *Post
}
func (p Post) Next() List{
return p.Next
}
...
//and then you can call Del() with any of this types
Del(post, 5)
Also Go have list data structure defined in stdlib which you can use.
Upvotes: 2