donkey199024 2016-10-20 14:34
浏览 35
已采纳

Go中的2D切片类型转换

I was constrained to define a particular type for []string because I implemented a custom yaml parser for the strSlice type.

Now I need to cast []strSlice back into [][]string but the go compiler 1.7.1 reject it as an error.

type strSlice []string
var x1 []strSlice
var x2 [][]string
...
x2 = [][]string(x1)

How can I perform the cast operation ?

  • 写回答

1条回答 默认 最新

  • duanli0119 2016-10-20 14:40
    关注

    You're using a named type of a string slice. You need to convert each entry in x1 back to a []string first:

    type strSlice []string
    var x1 []strSlice
    var x2 [][]string
    ...
    for _, s := range x1 {
        x2 = append(x2, []string(s))
    }
    

    https://play.golang.org/p/5iJT2Hsv1R

    Unfortunately, there's no way to do this in one shot, because each of the indexes in x1 are a strSlice type, and need to be converted to a []string type to be stored in x2. Go doesn't let you do this in a single operation because the developers didn't want to hide O(n) operations in syntactical sugar.

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

报告相同问题?

悬赏问题

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