Home >Common Problem >How to store in golang
The process of storage in golang is: 1. Create a Go sample file and import JSON data; 2. Define a Person structure type; 3. Start the program through the "main" function and read the name For all the data in the "people.json" file and store it in the data variable; 4. Create an empty Person type slice people and store the result in the &people pointer; 5. Output through "fmt.Printf()" The value of the people variable.
Operating system for this tutorial: Windows 10 system, Go1.20.1 version, Dell G3 computer.
Golang usually stores and reads data by using standard libraries and third-party libraries such as built-in encoding, json and database/sql.
Below we will introduce some sample code to demonstrate how to use these libraries to store and retrieve data.
Store to file:
The following is a sample code to store JSON data to a file:
package main import ( "encoding/json" "fmt" "io/ioutil" ) type Person struct { Name string `json:"name"` Age int `json:"age"` } func main() { people := []Person{ Person{"Alice", 25}, Person{"Bob", 30}, } data, err := json.Marshal(people) if err != nil { panic(err) } err = ioutil.WriteFile("people.json", data, 0644) if err != nil { panic(err) } fmt.Println("Data saved to file.") }
This example uses the json.Marshal() function Convert the People slice to JSON bytes and write to disk using ioutil.WriteFile().
Read file:
The following is a sample code that reads JSON data from a file and parses it into a structure slice:
package main import ( "encoding/json" "fmt" "io/ioutil" ) type Person struct { Name string `json:"name"` Age int `json:"age"` } func main() { data, err := ioutil.ReadFile("people.json") if err != nil { panic(err) } var people []Person err = json.Unmarshal(data, &people) if err != nil { panic(err) } fmt.Printf("%+v\n", people) }
The above is the detailed content of How to store in golang. For more information, please follow other related articles on the PHP Chinese website!