Write Files

  1. Writing a file using a struct and encoding data in JSON:

import (
    "encoding/json"
    "os"
)

type Data struct {
    Field1 string
    Field2 int
    // Add more fields as needed
}

// Example of writing data to file using JSON encoding
func writeToJSONFile(filename string, data Data) error {
    file, err := os.Create(filename)
    if err != nil {
        return err
    }
    defer file.Close()

    encoder := json.NewEncoder(file)
    if err := encoder.Encode(data); err != nil {
        return err
    }

    return nil
}
  1. Writing byte slices using os.Create and f.Write:

  1. Writing strings using f.WriteString():

  1. Using bufio to write data to a file:

  1. Using bufio to write line by line:

Example usage:

Last updated

Was this helpful?