【问题标题】:Golang remove dup ints from slice append function "evaluated but not used"Golang 从切片追加函数“已评估但未使用”中删除 dup ints
【发布时间】:2019-03-18 17:14:21
【问题描述】:

我无法运行这个 Go 语言测试程序。编译器在下面的 append() 函数调用中不断给出错误,并出现“已评估但未使用”错误。我不知道为什么。

package main

import (
    "fmt"
)

func removeDuplicates(testArr *[]int) int {

    prevValue := (*testArr)[0]
    for curIndex := 1; curIndex < len((*testArr)); curIndex++ {
        curValue := (*testArr)[curIndex]
        if curValue == prevValue {
            append((*testArr)[:curIndex], (*testArr)[curIndex+1:]...)
        }
        prevValue = curValue
    }
    return len(*testArr)
}

func main() {
    testArr := []int{0, 0, 1, 1, 1, 2, 2, 3, 3, 4}

    nonDupSize := removeDuplicates(&testArr)

    fmt.Printf("nonDupSize = %d", nonDupSize)
}

【问题讨论】:

标签: go append slice


【解决方案1】:

"evaluated but not used" error.

下面的代码是我的想法。我觉得你的代码不是很清楚。

package main

import (
    "fmt"
)

func removeDuplicates(testArr *[]int) int {
    m := make(map[int]bool)
    arr := make([]int, 0)

    for curIndex := 0; curIndex < len((*testArr)); curIndex++ {
        curValue := (*testArr)[curIndex]
        if has :=m[curValue]; !has {
            m[curValue] = true
            arr = append(arr, curValue)
        }
    }
    *testArr = arr
    return len(*testArr)
}

func main() {
    testArr := []int{0, 0, 1, 1, 1, 2, 2, 3, 3, 4}

    nonDupSize := removeDuplicates(&testArr)

    fmt.Printf("nonDupSize = %d", nonDupSize)
}

【讨论】:

    【解决方案2】:

    彼得的回答是肯定的,编译错误是由于没有从 append() 中获取返回值

    【讨论】:

      猜你喜欢
      • 2017-12-13
      • 2017-06-17
      • 2019-01-09
      • 2019-10-17
      • 2016-12-03
      • 2018-04-15
      • 1970-01-01
      • 2016-03-10
      • 2012-02-13
      相关资源
      最近更新 更多