英文:
iteration + casting in go
问题
我有一段代码片段,它在一个列表上使用了一个迭代器。
for x:= range s.faces.Iter(){
x.Render()
}
编译器指出,x的类型是interface{},而我的代码中没有定义一个方法(i interface)Render()。
将代码改为:
for x:= range s.faces.Iter(){
x.(faceTri).Render()
}
可以编译通过,因为有一个方法func (f faceTri) Render()。
但在执行时,会出现以下运行时错误:
panic: interface conversion: interface is *geometry.faceTri, not geometry.faceTri
(geometry是包名)
所以,有人可以指导我如何在Go语言中使用迭代器+类型转换的资源吗?
英文:
i have this snippet of code that use an iterator on a list
for x:= range s.faces.Iter(){
x.Render()
}
as the compiler points, x is of type interface{} and there isn't a method (i interface)Render() defined in my code.
changing to
for x:= range s.faces.Iter(){
x.(faceTri).Render()
}
compile, because there is a method func (f faceTri) Render()
but upon execution this runtime error is raised:
panic: interface conversion: interface is *geometry.faceTri, not geometry.faceTri
(geometry is the package)
so, anybody can point me to a resource that explain the go way to use iterators + casting?
答案1
得分: 3
那实际上在Go语言中被称为类型断言,而不是类型转换(类型转换是在编译时进行的某些兼容类型之间的转换,例如int -> int32)。
根据您发布的错误,您的代码中只有一个小错误。<code>x</code> 的底层类型是 <code>*faceTri</code>(指向faceTri结构的指针),所以类型断言应该是 <code>x.(*faceTri)</code>
编辑:
有几点需要澄清并超出您的问题。在Go语言中,类型断言不是类型转换,例如:<code>interface_with_underlying_type_int.(int64)</code> 会引发panic,即使<code>int</code> 可以转换为<code>int64</code>
此外,您可以使用逗号-ok惯用法来检查类型断言
<code>not_interface, ok := some_interface.(some_type)</code>
<code>ok</code> 是一个布尔值,指示转换是否成功,而不是引发运行时panic。
英文:
That's actually called a type assertion in go, not a cast (casts are compile time conversions between certain compatible type, i.e. int -> int32).
Based on the error you posted, you just have a tiny mistake in your code. The underlying type of <code>x</code> is <code>*faceTri</code> (a pointer to a faceTri structure), so the type assertion should be <code>x.(*faceTri)</code>
EDIT:
A few things to clarify and go beyond your question. A type assertion in go is not a cast, for example: <code>interface_with_underlying_type_int.(int64)</code> will panic, even though <code>int</code> can be cast to <code>int64</code>
Also, you can check a type assertion using the comma-ok idiom
<code>not_interface, ok := some_interface.(some_type)</code>
<code>ok</code> is a boolean indicating whether the conversion was successful, instead of causing a runtime panic.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论