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?
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
xis*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 thoughintcan be cast toint64Also, you can check a type assertion using the comma-ok idiom
not_interface, ok := some_interface.(some_type)okis a boolean indicating whether the conversion was successful, instead of causing a runtime panic.