“不支持索引”:使用接口提供索引?

时间:2016-10-06 16:02:48

标签: go

https://play.golang.org/p/qxhocI6mjY

在这出戏中,我收到此错误:FileNotFoundError: [WinError 3] The system cannot find the path specified: 'Deployment/Work/test2/src' 所以我想知道,是否可以实现索引?

给出这样的结构:

invalid operation: s[0] (type AlmostSlice does not support indexing)

是否可以使其支持索引?

type AlmostSlice struct {
    Entities []string
    Id       string
    Stuffs   string
}

例如,通过实现以下内容:

s := AlmostSlice{Id: "bar", Entities: []string{"foo"}}
... := s[0]
s[0] = "stuffs"

2 个答案:

答案 0 :(得分:1)

好问题。在其他语言中,你可以实现魔术接口来做类似的东西但是在Go中我们没有那些东西。所以要回答你的问题,从1.7开始就不能在结构上实现索引。

答案 1 :(得分:1)

你做不到。 Go的目标是简单并按照它所说的去做,而不是调用底层方法。如果它支持索引,那么它是一个切片/数组,一个字符串或一个映射。所以你可以做this,虽然它可能不是你想要的。

出于这个原因,我建议你简单地按照你在问题中建议的那样做,即有一个方法从实体中选择一个元素:

struct node{
         int x, y, val;
         node(int _x, int _y, int _val){
             x = _x;
             y = _y;
             val = _val;
         }
         node(){}

        bool operator () (const node& lhs, const node& rhs) const{
         return lhs.val > rhs.val;
     }
 };

priority_queue<node, vector<node>, node> queue;

就目前而言,就是目前最好的方式。