【问题标题】:Go Golang : Type assertion on customized typeGo Golang:自定义类型的类型断言
【发布时间】:2014-01-12 05:12:25
【问题描述】:

http://play.golang.org/p/icQO_bAZNE

我正在练习使用堆排序,但是

  prog.go:85: type bucket is not an expression
  prog.go:105: cannot use heap.Pop(bucket[i].([]IntArr)) (type interface {}) as type int in assignment: need type assertion
  [process exited with non-zero status]

我遇到了这些错误,不知道如何正确键入 assert

问题出在以下几行:

  heap.Push(bucket[x].([]IntArr), elem)

  arr[index] = heap.Pop(bucket[i].([]IntArr))

因为我想使用堆结构来从每个桶中提取值

每个桶都是[]IntArr

IntArr[]int,如下所示

type IntArr []int
type bucket [10]IntArr

周末尝试了很多方法,还是搞不定,非常感谢。

【问题讨论】:

    标签: types interface go type-conversion


    【解决方案1】:

    要使用 heap 包,您应该为您的类型实现 heap.Interface(在本例中,为您的 IntArr 类型)。您可以在这里找到示例:http://golang.org/pkg/container/heap/#pkg-examples

    然后你可以做类似的事情

    heap.Push(bucket[x], elem)
    

    【讨论】:

    【解决方案2】:

    来自go spec

    对于接口类型 x 和类型 T 的表达式,主 表达

    x.(T)

    断言 x 不是 nil 并且存储在 x 中的值是 T 类型。 符号 x.(T) 称为类型断言。

    bucket[x] 不是接口类型的表达式,查看更多here

    【讨论】:

    • 是的,你是对的,但我不知道如何使 bucket[x] 成为具有类型断言的接口类型,我没有做到这一点。您能简要解释一下您将如何更改我的代码吗?
    • @MaynardEPSILON 我认为您应该考虑@kluyg 所说的关于实现heap.Interface 而不是任何类型断言的内容。
    猜你喜欢
    • 2014-01-22
    • 1970-01-01
    • 2019-11-06
    • 2014-01-08
    • 2019-01-01
    • 2019-11-03
    • 1970-01-01
    • 1970-01-01
    • 2015-03-10
    相关资源
    最近更新 更多