douhui1630 2010-07-16 14:16
浏览 38
已采纳

迭代+强制转换

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条回答 默认 最新

  • duangu1878 2010-07-16 14:53
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度