迭代+在 Go 中铸造
我有这段代码,它使用列表上的迭代器
for x:= range s.faces.Iter(){
x.Render()
}
作为编译器点,x 的类型为interface{},并且我的代码中没有定义方法 (i interface)Render() 。
改为
for x:= range s.faces.Iter(){
x.(faceTri).Render()
}
compile,因为有一个方法 func (f faceTri) Render() 但在执行时会引发此运行时错误:
panic:interface conversion:interface is *geometry.faceTri, notometry.faceTri
(geometry is the package)
所以,任何人都可以向我指出一个解释使用迭代器+转换的方法的资源?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这实际上在 go 中称为类型断言,而不是强制转换(强制转换是某些兼容类型之间的编译时转换,即 int -> int32)。
根据您发布的错误,您的代码中只有一个小错误。
x
的底层类型是*faceTri
(指向faceTri 结构的指针),因此类型断言应该是x.(*faceTri)
编辑:
有一些事情需要澄清并超越你的问题。 go 中的类型断言不是强制转换,例如:
interface_with_underlying_type_int.(int64)
会发生恐慌,即使int
可以强制转换为int64
另外,您可以使用逗号-ok 惯用语检查类型断言
not_interface, ok := some_interface.(some_type)
ok
是一个布尔值,指示转换是否成功,而不是导致运行时恐慌。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
x
is*faceTri
(a pointer to a faceTri structure), so the type assertion should bex.(*faceTri)
EDIT:
A few things to clarify and go beyond your question. A type assertion in go is not a cast, for example:
interface_with_underlying_type_int.(int64)
will panic, even thoughint
can be cast toint64
Also, you can check a type assertion using the comma-ok idiom
not_interface, ok := some_interface.(some_type)
ok
is a boolean indicating whether the conversion was successful, instead of causing a runtime panic.