go - convert int array to byte array in Golang -


i'm trying create random int arrays , write xyz.txt file in golang.
how convert ids int array byte array, file.write accepts []byte parameter. correct way achieve writing random integer arrays text file.

func main() {     var id int     var ids []int     var count int      f, err := os.create("xyz.txt")     check(err)      defer f.close()      j := 0; j < 5; j++ {         count = rand.intn(100)         := 0; < product_count; i++ {             id = rand.intn(1000)             ids = append(product_ids, product_id)         }         n2, err := f.write(ids)         check(err)         fmt.printf("wrote %d bytes\n", n2)     } } 

you may use fmt.fprint, simplified working sample:

package main  import (     "bufio"     "fmt"     "math/rand"     "os" )  func main() {     f, err := os.create("xyz.txt")     if err != nil {         panic(err)     }     defer f.close()     w := bufio.newwriter(f)     defer w.flush()      j := 0; j < 5; j++ {         count := 4 //count := rand.intn(100)         := 0; < count; i++ {             fmt.fprint(w, rand.intn(1000), " ")         }         fmt.fprintln(w)     } } 

xyz.txt output file:

81 887 847 59  81 318 425 540  456 300 694 511  162 89 728 274  211 445 237 106  

Comments

Popular posts from this blog

How to use SUM() in MySQL for calculated values -

loops - Spock: How to use test data with @Stepwise -