types - 去Go语言: Type assertion on customized type

标签 types interface go type-conversion

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]

我收到这些错误,并且不知道如何正确键入断言

问题出在以下几行:

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

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

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

每个桶都是[]IntArr

并且IntArr[]int,如下所示

type IntArr []int
type bucket [10]IntArr

周末我尝试了很多方法,但无法弄清楚,我非常感激。

最佳答案

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

然后你可以做类似的事情

heap.Push(bucket[x], elem)

关于types - 去Go语言: Type assertion on customized type,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20752772/

相关文章:

C++ 字符问题

c# - C#中的幂等接口(interface)方法

java - 在 Java 中显式调用默认方法

不需要它的Java泛型名称类型参数

types - 数据类型编程

go - 如何导出名称以便全局访问?

go - 为什么我会出现死锁?

callback - 如何对 interface{} 变量进行类型断言以测试它是否是函数?

Java 协变返回类型不适用于枚举实例的覆盖方法?

java - 何时初始化具有默认方法的接口(interface)?