How to store go channel value into some other data type(string,byte[]) and reassign it other go channel

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

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]]

Playground

英文:

The code below will convert an incoming string into an outgoing byte-slice. Hopefully that's what you're after:

package main

import &quot;fmt&quot;

func stringToByteSlice(sc chan string, bc chan []byte) {
	defer close(bc)
	for s := range sc {
		bc &lt;- []byte(s)
	}
}

func main() {
	strings := []string{&quot;foo&quot;, &quot;bar&quot;, &quot;baz&quot;, &quot;bat&quot;}
	byteSlices := [][]byte{}
	sc := make(chan string)
	bc := make(chan []byte)
	go func() {
		defer close(sc)
		for _, s := range strings {
			sc &lt;- s
		}
	}()
	go stringToByteSlice(sc, bc)
	for b := range bc {
		byteSlices = append(byteSlices, b)
	}
	fmt.Printf(&quot;%v\n&quot;, byteSlices)
}

Outputs:

>[[102 111 111] [98 97 114] [98 97 122] [98 97 116]]

Playground

huangapple
  • 本文由 发表于 2014年5月3日 09:15:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/23439157.html
匿名

发表评论

匿名网友

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

确定