使用类型别名将Go数组转换为指定类型。

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

cast go array with type alias

问题

假设我有一个定义好的类型 Bytes,它是一个字节数组,如下所示。是否有一种简单的方法可以将一个字节数组的数组转换为一个 Bytes 数组,反之亦然?

package main

type Bytes []byte

func main() {
    x := make([][]byte, 3)
    y := ([]Bytes)(x)
}

以下是翻译好的内容:

假设我有一个定义好的类型 Bytes,它是一个字节数组,如下所示。是否有一种简单的方法可以将一个字节数组的数组转换为一个 Bytes 数组,反之亦然?

package main

type Bytes []byte

func main() {
    x := make([][]byte, 3)
    y := ([]Bytes)(x)
}
英文:

Say I have a defined type Bytes that is a bytes array as in below. Is there a simple way to convert an array of arrays of byte to an array of Bytes and vice versa?

package main

type Bytes []byte

func main() {
	x := make([][]byte, 3)
	y := ([]Bytes)(x)
}

答案1

得分: 2

有没有一种简单的方法将字节数组的数组转换为字节数组的数组?

通过使用实际的别名,你可以实现这个目标。然而,Bytes并不是一个别名,它是一个与[]byte具有相同底层类型的不同类型。在这种情况下,唯一的选择是使用循环。

另请参阅如果T1T2具有相同的底层类型,我可以将[]T1转换为[]T2吗?

英文:

> Is there a simple way to convert an array of arrays of byte to an array of Bytes

With an actual alias you could do it. Bytes however is not an alias, it is a distinct type that only has the underlying type common with []byte. The only option in this case is to use a loop.

See also Can I convert []T1 to []T2 if T1 and T2 have the same underlying type?.

答案2

得分: 1

不好意思,我之前的回答有误。以下是翻译好的内容:

不幸的是,Go语言不允许直接在不同类型之间进行转换,即使它们是别名。别名更像是给现有类型起一个新名字,但它并不提供任何形式的自动转换。

你需要手动迭代**[][]byte并将每个[]byte转换为Bytes**类型。

下面是如何实现的示例代码:

package main

import "fmt"

type Bytes []byte

func main() {
    x := make([][]byte, 3)
    // 为演示目的初始化字节切片
    for i := range x {
        x[i] = []byte{byte(i), byte(i+1)}
    }

    y := make([]Bytes, len(x))
    for i, v := range x {
        y[i] = Bytes(v)
    }

    fmt.Println("Hello, 世界", y)
}

这段代码手动迭代x,将每个**[]byte转换为Bytes类型,并将其放置在y**的相应位置上。

英文:

No, unfortunately Go does not allow direct conversion between different types, even if they are aliases. Alias is more like giving a new name to an existing type, but it does not provide any form of automatic conversion.

You need to manually iterate over the [][]byte and convert each []byte to Bytes type.

Here's how you can do it:

package main

import "fmt"

type Bytes []byte

func main() {
    x := make([][]byte, 3)
    // Initializing byte slices for demonstration purposes
    for i := range x {
        x[i] = []byte{byte(i), byte(i+1)}
    }

    y := make([]Bytes, len(x))
    for i, v := range x {
        y[i] = Bytes(v)
    }

    fmt.Println("Hello, 世界", y)
}

This code manually iterates over x, converting each []byte to Bytes and placing it in the corresponding position in y.

huangapple
  • 本文由 发表于 2023年6月27日 15:08:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/76562391.html
匿名

发表评论

匿名网友

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

确定