Golang类型转换规则

huangapple go评论94阅读模式
英文:

golang type cast rule

问题

以下是翻译好的内容:

以下代码生成了一个错误:

./main.go:12: 无法将类型为 []map[string]interface {} 的 data 作为参数传递给 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)),Go 会报错:

./main.go:12: 无法将类型为 []map[string]interface {} 的 data 转换为类型 Rows

然而,以下版本可以成功编译:

package main

type Rows []map[string]interface{}

func do(data Rows) {}

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

有人能解释为什么吗?在第一种情况下,有没有正确的方法来进行类型转换?

英文:

The following code generated an error:

./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)
}

If I try to do a type cast, e.g. do(Rows(data)), go said:

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

However, the following version compiles OK:

package main

type Rows []map[string]interface{}

func do(data Rows) {}

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

Could anyone explain why? In the first case, is there any proper way to do the typecast?

答案1

得分: 2

对于“为什么”,请参考mkopriva发布的链接。以下答案是关于您原始情况的。

在第一种情况下,您可以逐个将map[string]interface{}进行类型转换(循环遍历它们),然后将[]Row转换为Rows。您不能一次性将整个内容进行转换。从[]RowRows的转换可以隐式完成。

这是您的测试片段,其中描述了转换的方式。

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))  // 可行但不必要
	do(rws)        // 这样也可以正常工作
	do(rows)
}
英文:

For "why" see the link posted by mkopriva. The following answer is regarding your original case.

In the first case you could cast each map[string]interface{} individually (looping over them) and then cast []Row to Rows. You cannot cast the whole thing at once. The cast from []Row to Rows can be done implicitly.

Here your test snippet with the described ways to cast it.

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)
}

huangapple
  • 本文由 发表于 2017年8月1日 16:38:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/45432904.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定