dongyi2083 2014-02-11 05:09
浏览 118

Golang实现一个链表

I'm trying to implement a sorted linked list in golang. And I'm having a hard time coming up with a generic way to make the linked list work with any type that can by compared with itself. Since its a sorted list, I want the 'go compiler' to ensure that the values being inserted into the linked list can be compared.

For example,

import "linkedlist"

type Person struct {
  name string
}

func main() {
  l := linkedlist.New()
  p := Person{"Jay"}
  l.insert(p)
}

In the above example, how do I make the compiler ensure that the value 'p' which has type 'Person' can be compared with another value which also has type 'Person'. I want the compiler to catch the error in those situations where the value being inserted is not an appropriate value.

I can do something like this,

import "linkedlist"

type Element interface {
  func IsGreater(v Element{}) bool
}

type Person struct {
  name string
  age int
}

func (p *Person) IsGreater(p1 interface{}) bool {
  if ok, v := p1.(Person); ok && p.age > v.age {
    return true
  }
  return false
}

And then, within the "insert" function of the linked list I can use the IsGreater function to decide where to place the Element in the linked list.

My question is...

  1. Is there a better way to do this? Something that is a lot better than the solution above.

I've already gone through sort.Sort and seen how its done in that package. The way its done there is to create a new type for a slice of the type and then make that new type fulfill the sort interface by implementing Len, Less and Swap.

I can probably do the same thing here in my case as well. But having to create a new slice type and then implement a few functions to satisfy an interface, when I'll only be dealing with 2 values of the same type at a time.. seems a bit overkill to me.

  • 写回答

2条回答

  • duanhe3393 2014-02-11 07:20
    关注

    Because Golang do not support generics, So all of containers should use interface{} and type assert, I think no better solution for your requirement.

    评论

报告相同问题?

悬赏问题

  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图