简体   繁体   中英

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

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

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

Playground

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM