go - 在 Golang 中将 int 数组转换为字节数组

标签 go

我正在尝试创建一些随机 int 数组并将其写入 Golang 中的 xyz.txt 文件。
如何将作为 int 数组的 ids 转换为 byte 数组,因为 file.Write 接受 [ ]byte 作为参数。实现将随机整数数组写入文本文件的正确方法是什么。

func main() {
    var id int
    var ids []int
    var count int

    f, err := os.Create("xyz.txt")
    check(err)

    defer f.Close()

    for j := 0; j < 5; j++ {
        count = rand.Intn(100)
        for i := 0; i < 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)
    }
}

最佳答案

您可以使用 fmt.Fprint,作为这个简化的工作示例:

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()

    for j := 0; j < 5; j++ {
        count := 4 //count := rand.Intn(100)
        for i := 0; i < count; i++ {
            fmt.Fprint(w, rand.Intn(1000), " ")
        }
        fmt.Fprintln(w)
    }
}

xyz.txt 输出文件:

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

关于go - 在 Golang 中将 int 数组转换为字节数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39202150/

相关文章:

go - 删除结构中 slice 的元素

arrays - 接受任意大小数组作为参数的函数(在 Golang 中可能吗?)

templates - 什么是正确的文件扩展名或缩写。对于 golang 的文本/模板?

http - 如何判断 net/http 的 ResponseWriter.Write() 是否已被调用?

web-applications - golang 网络编程教程代码不起作用

GORM 不会将 bool 字段更新为 false

go - golang ast遍历中如何从子节点检索父节点?

go - 如何在http客户端上使用Socks4

go - 给接口(interface)赋值会复制什么吗?

golang 意外的目录布局