douzhongpi9734 2014-04-29 01:01
浏览 51

当T2具有基本类型T1时,从[] T1转换为[] T2

Two closely related question:

Why doesn't Go Specification allow you to convert []T1 to []T2 if T2 has the underlying type of T1?

What are the negative consequences of doing the conversion using the unsafe package?

Example:

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
}

Playground: http://play.golang.org/p/x2tBRKuRF1

Example of usage:

If T1 implements a certain interface, say json.Marshaler, and you want to JSON encode the type in a different way, you create a new type T2 T1 with its own implementation of json.Marshaler.

It works fine when marshaling single values, but when you get a []T1 slice you would have to either copy it to a []T2 slice or create a new type ST1 []T1 with its own MarshalJSON() method. It would be nice to do a simple conversion instead instead of having to turn to unsafe as it might result in runtime errors instead of compile time.

  • 写回答

1条回答 默认 最新

  • doudouxuqh198138 2014-04-29 01:43
    关注

    The Go Programming Language Specification

    Conversions

    A non-constant value x can be converted to type T if x's type and T have identical underlying types.

    For example,

    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
    }
    

    Output:

    [{42}]
    [{42}]
    
    评论

报告相同问题?

悬赏问题

  • ¥15 目详情-五一模拟赛详情页
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line