簡體   English   中英

Go Golang:自定義類型上的類型斷言

[英]Go Golang : Type assertion on customized type

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

周末我一直在嘗試許多方法,無法弄清楚,對此我非常感謝。

go spec

對於具有接口類型和類型T的表達式x,主要表達式

x.(T)

斷言x不為nil,並且x中存儲的值的類型為T。符號x。(T)稱為類型斷言。

bucket[x]不是接口類型的表達式,請參見此處

要使用堆包,您應該為您的類型實現heap.Interface(在這種情況下,對於IntArr類型)。 您可以在此處找到示例: http : //golang.org/pkg/container/heap/#pkg-examples

然后你可以做類似的事情

heap.Push(bucket[x], elem)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM