开发者

iteration + casting in 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 t开发者_开发问答here 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 x is *faceTri (a pointer to a faceTri structure), so the type assertion should be x.(*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 though int can be cast to int64

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜