两个密切相关的问题:
为什么Go规格不允许您将[]T1转换为[]T2如果T2具有底层的T1类型
使用unsafe包进行转换的负面后果是什么?
示例:
package main
import (
"fmt"
"unsafe"
)
type T1 struct {
Val int
}
// T2 has the underlying type of T1
type T2 T1
func main() {
a := []T1{T1{12}}
// cannot convert a (type []T1) to type []T2
//b := ([]T2)(a)
// But with some unsafe we can do it.
// So, why doesn't Go allow it? And what unforeseen consequence might it have?
b := *(*[]T2)(unsafe.Pointer(&a))
b[0].Val = 42
fmt.Println(a[0].Val) // 42
}游乐场: http://play.golang.org/p/x2tBRKuRF1
用法示例:
如果T1实现了一个特定的接口,比如json.Marshaler,并且您想以不同的方式对该类型进行编码,那么您可以使用它自己的json.Marshaler实现创建一个新的type T2 T1。
当封送单个值时,它工作得很好,但是当您得到一个[]T1切片时,您必须要么将它复制到一个[]T2片,要么用它自己的MarshalJSON()方法创建一个新的type ST1 []T1。最好是做一个简单的转换,而不是转向unsafe,因为它可能导致运行时错误,而不是编译时。
发布于 2014-04-29 01:43:43
Go程序设计语言规范 转换 如果x的类型和T具有相同的基础类型,则可以将非常数值x转换为T类型。
例如,
package main
import (
"fmt"
)
type T1 struct {
Val int
}
type T2 T1
type ST1 []T1
type ST2 ST1
func main() {
a := ST1{T1{42}}
fmt.Println(a) // 42
// convert a (type ST1) to type []ST2
b := ST2(a)
fmt.Println(b) // 42
}输出:
[{42}]
[{42}]https://stackoverflow.com/questions/23353757
复制相似问题