//Target --> 将str(或一些byte[])转换成 channel 变量newpipe。 我必须将我的数据从一个进程传输到另一个我制作 xml 的进程。 Xml marshall 不支持 chan 类型也不适用于 interface{} 然后在从其他进程接收到响应 xml 后,将值分配给 newpipe 并使用 newpipe 进行 channel 通信
func main() {
mypipe := make(chan int)
fmt.Printf("My pipe addr %p \n", mypipe)
str := fmt.Sprintf("%p", mypipe) //way to convert mypipe to byte[]
var newpipe chan int
}
有一天我正在寻找各种类型转换,但没有一个适用于 chan 类型
最佳答案
下面的代码会将传入的字符串转换为传出的 byte slice 。希望这就是您所追求的:
package main
import "fmt"
func stringToByteSlice(sc chan string, bc chan []byte) {
defer close(bc)
for s := range sc {
bc <- []byte(s)
}
}
func main() {
strings := []string{"foo", "bar", "baz", "bat"}
byteSlices := [][]byte{}
sc := make(chan string)
bc := make(chan []byte)
go func() {
defer close(sc)
for _, s := range strings {
sc <- s
}
}()
go stringToByteSlice(sc, bc)
for b := range bc {
byteSlices = append(byteSlices, b)
}
fmt.Printf("%v\n", byteSlices)
}
输出:
[[102 111 111] [98 97 114] [98 97 122] [98 97 116]]
关于go - 如何将 go channel 值存储到其他数据类型(字符串,byte [])并将其重新分配给其他 go channel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23439157/