golang型演员规则

时间:2017-08-01 08:38:52

标签: go casting

以下代码生成错误:

./main.go:12: cannot use data (type []map[string]interface {}) as type Rows in argument to do

package main

type (
    Row  map[string]interface{}
    Rows []Row
)

func do(data Rows) {}

func main() {
    var data []map[string]interface{}
    do(data)
}

如果我尝试进行类型转换,例如do(Rows(data)),去说:

./main.go:12: cannot convert data (type []map[string]interface {}) to type Rows

但是,以下版本编译正常:

package main

type Rows []map[string]interface{}

func do(data Rows) {}

func main() {
    var data []map[string]interface{}
    do(data)
}

有人可以解释为什么吗?在第一种情况下,是否有任何正确的方法来进行类型转换?

1 个答案:

答案 0 :(得分:2)

为了"为什么"见link posted by mkopriva。以下答案与您的原始案例有关。

在第一种情况下,您可以单独投射每个map[string]interface{}(循环播放它们),然后将[]Row投射到Rows。你不能立刻抛出整个东西。从[]行到行的转换可以隐式完成。

这里是你的test snippet,其中描述了投射它的方法。

package main

type (
    Row  map[string]interface{}
    Rows []Row
)

func do(data Rows) {}

func main() {
    var (
        data []map[string]interface{}
        rws []Row
        rows Rows
    )
    for _, r := range data {
        rws = append(rws, Row(r))
        rows = append(rows, Row(r))
    }
    do(Rows(rws))  // possible but not necessary
    do(rws)        // this works just fine
    do(rows)
}
相关问题