2013-12-23 23:31
浏览 249

Go Golang:自定义类型上的类型断言


I am practicing sort using heap but

  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]

I am getting those errors and can't figure out how to type assert properly

The problem is from the lines:

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

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

Because I want to use heap structure in order to extract values from each bucket

And each bucket is []IntArr

And IntArr is []int like the following

type IntArr []int
type bucket [10]IntArr

I have been trying many ways over the weekend and can't figure out, I greatly appreciate it.

图片转代码服务由CSDN问答提供 功能建议



 prog.go:105:无法使用heap.Pop(bucket [i]。([[IntArr))(type interface {})作为int中的int类型:需要 键入断言



  heap.Push(bucket [x]。([] IntArr),elem)
 arr  [index] = heap.Pop(bucket [i]。([[IntArr))

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

每个存储桶为 [] IntArr

,而 IntArr [] int 如下所示

  type IntArr [] int 
type bucket [10] IntArr 

我一直在尝试 周末有很多方法,无法解决,我非常感谢。

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dream890110
    dream890110 2013-12-24 00:00

    To use heap package you should implement heap.Interface for your type (in this case, for your IntArr type). You can find example here: http://golang.org/pkg/container/heap/#pkg-examples

    Then you can do things like

    heap.Push(bucket[x], elem)
    点赞 评论
  • doumin1897
    doumin1897 2013-12-23 23:56

    From go spec:

    For an expression x of interface type and a type T, the primary expression


    asserts that x is not nil and that the value stored in x is of type T. The notation x.(T) is called a type assertion.

    bucket[x] is not an expression of an interface type, see more here.

    点赞 评论