doutao4938 2017-01-29 17:28
浏览 42

如何使用通用结构

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
    }
}
  • 写回答

2条回答 默认 最新

  • drl9940 2017-01-29 18:24
    关注

    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.

    评论

报告相同问题?

悬赏问题

  • ¥15 Python输入字符串转化为列表排序具体见图,严格按照输入
  • ¥20 XP系统在重新启动后进不去桌面,一直黑屏。
  • ¥15 opencv图像处理,需要四个处理结果图
  • ¥15 无线移动边缘计算系统中的系统模型
  • ¥15 深度学习中的画图问题
  • ¥15 java报错:使用mybatis plus查询一个只返回一条数据的sql,却报错返回了1000多条
  • ¥15 Python报错怎么解决
  • ¥15 simulink如何调用DLL文件
  • ¥15 关于用pyqt6的项目开发该怎么把前段后端和业务层分离
  • ¥30 线性代数的问题,我真的忘了线代的知识了