英文:
Go Golang : Type assertion on customized type
问题
我正在使用堆排序进行练习,但是我遇到了以下错误:
prog.go:85: 类型bucket不是一个表达式
prog.go:105: 无法将heap.Pop(bucket[i].([]IntArr))(类型为interface {})作为int类型的赋值:需要类型断言
[进程以非零状态退出]
我得到了这些错误,但是无法弄清楚如何正确进行类型断言。
问题出在以下几行代码上:
heap.Push(bucket[x].([]IntArr), elem)
arr[index] = heap.Pop(bucket[i].([]IntArr))
因为我想使用堆结构来从每个桶中提取值
每个桶是[]IntArr
而IntArr
是[]int
,如下所示:
type IntArr []int
type bucket [10]IntArr
我在周末尝试了很多方法,但是无法解决,非常感谢。
英文:
http://play.golang.org/p/icQO_bAZNE
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.
答案1
得分: 2
根据go spec中的说明:
对于一个接口类型的表达式x和一个类型T,主表达式
x.(T)
断言x不是nil,并且存储在x中的值是类型T的。x.(T)的表示法称为类型断言。
bucket[x]
不是一个接口类型的表达式,可以在这里了解更多信息。
英文:
From go spec:
> For an expression x of interface type and a type T, the primary
> expression
> x.(T)
> 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.
答案2
得分: 2
要使用堆包(heap package),你需要为你的类型(在这种情况下,是你的IntArr类型)实现heap.Interface接口。你可以在这里找到一个例子:http://golang.org/pkg/container/heap/#pkg-examples
然后你可以进行如下操作:
heap.Push(bucket[x], elem)
英文:
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论