首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >当[]T1具有基础类型T1时,从[]T1转换为[]T1

当[]T1具有基础类型T1时,从[]T1转换为[]T1
EN

Stack Overflow用户
提问于 2014-04-29 01:01:34
回答 1查看 98关注 0票数 1

两个密切相关的问题:

为什么Go规格不允许您将[]T1转换为[]T2如果T2具有底层的T1类型

使用unsafe包进行转换的负面后果是什么?

示例:

代码语言:javascript
复制
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,因为它可能导致运行时错误,而不是编译时。

EN

回答 1

Stack Overflow用户

发布于 2014-04-29 01:43:43

Go程序设计语言规范 转换 如果x的类型和T具有相同的基础类型,则可以将非常数值x转换为T类型。

例如,

代码语言:javascript
复制
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
}

输出:

代码语言:javascript
复制
[{42}]
[{42}]
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/23353757

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档