英文:
How to store go channel value into some other data type(string,byte[]) and reassign it other go channel
问题
//目标-->将字符串(或某些字节数组)转换为通道变量newpipe。
我必须通过创建XML将我的数据从一个进程传输到另一个进程。
XML编组不支持chan类型,也不支持interface{}类型。
然后,在从其他进程接收响应XML后,将值分配给newpipe,并使用newpipe进行通道通信。
func main() {
mypipe := make(chan int)
fmt.Printf("我的管道地址 %p \n", mypipe)
str := fmt.Sprintf("%p", mypipe) //将mypipe转换为字节数组的方法
var newpipe chan int
}
我已经寻找了各种类型转换方法一整天,但没有一种方法适用于chan类型。
英文:
//Target --> convert str(or some byte[])into channel variable newpipe.
I have to transfer my data from one process to another my making xml.
Xml marshall does not support chan type does not work with interface{} also
then after receveing response xml from other process assign value to newpipe and use newpipe for channel communication
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
}
I am looking for various type conversion for one day but none of them works with chan type
答案1
得分: 2
下面的代码将把输入的字符串转换为输出的字节切片。希望这正是你想要的:
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]]
英文:
The code below will convert an incoming string into an outgoing byte-slice. Hopefully that's what you're after:
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)
}
Outputs:
>[[102 111 111] [98 97 114] [98 97 122] [98 97 116]]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论