duanputian5341 2017-03-12 20:09
浏览 37
已采纳

Go中的惯用拼接

I checked an existing answer but it's not similar to my case.

I need to pluck an element at the index and break out of the for loop at runtime based on Compare function.

Issues: If element to pluck is found at 0 index, index-1 will throw slice bounds of range error and similarly if index+1 is greater than len(elements).

Question: What's the best concise way to achieve the above?

for index, element := range elements {
    if element.Compare() == true {
        elements = append(elements[:index-1], elements[index+1:]...)
        break
    }
}

Attempt

for index, element := range elements {
    if element.Compare() == true {
        if len(elements) > 1 {
            elements = append(elements[:index-1], elements[index+1:]...)
        } else if len(elements) == 1 {
            delete(elements, 0)
        }
        break
    }
}

Attempt 2 Playground any improvements/suggestions?

The idea is to copy the remaining elements from beginning to index and then any elements after.

var elements = []string {"a", "b", "c", "d"}
fmt.Println(elements)
for index, element := range elements {
    if element == "c" {
        var temp = elements[:index]
        for i := index + 1; i<len(elements); i++ {
            temp = append(temp, elements[i])
        }
        elements = temp
        break
    }
}
fmt.Println(elements)
  • 写回答

2条回答 默认 最新

  • donglao7947 2017-03-12 20:40
    关注

    The high index in a slice expression is exclusive.

    This means your example is flawed, and also that no special treatment is required.

    The correct slicing expression is:

    elements = append(elements[:index], elements[index+1:]...)
    

    If index is the first element (0), then elements[:0] will be an empty slice.

    If index is the last element (len-1), then elements[index+1:] will also be an empty slice, as index+1 will be equal to the lenght of the slice. So the solution is simply:

    for index, element := range elements {
        if element.Compare() {
            elements = append(elements[:index], elements[index+1:]...)
            break
        }
    }
    

    To demonstrate it on the Go Playground, let's substitute the Compare() method with a simple index check:

    for _, idxToRemove := range []int{0, 2, 4} {
        s := []int{0, 1, 2, 3, 4}
        for i := range s {
            if i == idxToRemove {
                s = append(s[:i], s[i+1:]...)
                break
            }
        }
        fmt.Println(idxToRemove, ":", s)
    }
    

    Output (try it on the Go Playground):

    0 : [1 2 3 4]
    2 : [0 1 3 4]
    4 : [0 1 2 3]
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题