6

我正在尝试使用此处的删除示例从切片中删除多个项目:http ://code.google.com/p/go-wiki/wiki/SliceTricks 这是我拥有的代码:

package main

import "fmt"
import "net"

func main() {
    a := []string{"72.14.191.202", "69.164.200.202", "72.14.180.202", "2600:3c00::22", "2600:3c00::32", "2600:3c00::12"}
    fmt.Println(a)
    for index, element := range a {
        if net.ParseIP(element).To4() == nil {
            //a = append(a[:index], a[index+1:]...)
            a = a[:index+copy(a[index:], a[index+1:])]
        }
    }
    fmt.Println(a)
}

如果切片中只有一个 IPv6 地址,则代码可以正常工作,但如果有多个 IPv6 地址,则代码会失败。它失败并出现错误“恐慌:运行时错误:切片边界超出范围”。我应该怎么做才能修复此代码,以便它能够删除所有 IPv6 地址?

4

2 回答 2

15

您的问题是您正在修改您正在迭代的切片。以下是您的代码稍作修改:

package main

import (
    "fmt"
    "net"
)

func main() {
    a := []string{"72.14.191.202", "69.164.200.202", "72.14.180.202", "2600:3c00::22", "2600:3c00::32", "2600:3c00::12"}
    fmt.Println(a)
    for i := 0; i < len(a); i++ {
        if net.ParseIP(a[i]).To4() == nil {
            a = append(a[:i], a[i+1:]...)
            //a = a[:i+copy(a[i:], a[i+1:])]
            i-- // Since we just deleted a[i], we must redo that index
        }
    }
    fmt.Println(a)
}

操场

于 2013-11-13T12:47:25.890 回答
2

只是提出一点:改变你正在迭代的结构总是很棘手。
避免这种情况的常用方法是在新变量中构建最终结果:

package main

import (
    "fmt"
    "net"
)

func main() {
    a := []string{"72.14.191.202", "69.164.200.202", "72.14.180.202", "2600:3c00::22", "2600:3c00::32", "2600:3c00::12"}
    fmt.Println(a)

    var b []string
    for _, ip := range a {
        if net.ParseIP(ip).To4() != nil {
                b = append(b, ip)
        }
    }
    fmt.Println(b)
}

http://play.golang.org/p/7CLMPw_FQi

于 2013-11-13T13:38:55.680 回答