The reflection of Golang

First, about reflection

  • The reflection function has a powerful function
  • Reflection is the ability to programmatically examine the structure, especially the type, it has
  • This is a form of metaprogramming
  • We can analyze a structure at run time by reflection
  • Check its types and variables (types and values) and methods
  • Dynamically modify variables and invoke methods
  • This is especially useful for packages without source code
  • It’s a powerful tool,

Here is the source code for exporting goods to a specific JSON file

package main

import (
	"encoding/json"
	"fmt"
	"os"
)

type Computer struct {
	Name string
	Price float64
	Cpu string
	Memory int
	Disk int
}
type Tshirt struct {
	Name string
	Price float64
	Color string
	Size int
	Sex bool
}
type Car struct {
	Name string
	Price float64
	Cap int
	Power string
}
func main(a) {
	products := make([]interface{},0)
	products = append(products, Computer{"Destroyer".9.9."i7".32.2048})
	products = append(products, Tshirt{"Bad clothes Bank".88."Red".40.false})
	products = append(products, "Tesla".237811.5."Hybrid oil and electric")

	EncodeObjToJsonFile(products,"E:\\code\\src\\jsonFile\\products.json")}func EncodeObjToJsonFile(objs []interface{},filename string) bool  {
	dstFile, _ := os.OpenFile(filename, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
	defer dstFile.Close()

	encoder := json.NewEncoder(dstFile)
	err := encoder.Encode(objs)
	if err == nil{
		fmt.Println("Success")
		return true
	}else{
		fmt.Println("Failure")
		return false}}Copy the code

The command output is successful.

Here is the output JSON file

We can then go to www.json.cn/ to see the formatted JSON.

Export the product to a JSON file with the same name

package main

import (
	"encoding/json"
	"fmt"
	"os"
	"reflect"
)

type Computer struct {
	Name string
	Price float64
	Cpu string
	Memory int
	Disk int
}
type Tshirt struct {
	Name string
	Price float64
	Color string
	Size int
	Sex bool
}
type Car struct {
	Name string
	Price float64
	Cap int
	Power string
}
func main(a) {
	products := make([]interface{},0)
	products = append(products, Computer{"Destroyer".9.9."i7".32.2048})
	products = append(products, Tshirt{"Bad clothes Bank".88."Red".40.false})
	products = append(products, Car{"Tesla".237811.5."Hybrid oil and electric"})
	for _,p := range products{
		pValue := reflect.ValueOf(p)
		name := pValue.FieldByName("Name").Interface()
		fmt.Println(name)
		EncodeObjToJsonFile(p,"E: \ \ block chain palace road \ \ 01.0 _Go language - v3.0 \ \ code \ \ SRC \ \ jsonFile \ \"+ name.(string) +".json")}}func EncodeObjToJsonFile(obj interface{},filename string) bool  {
	dstFile, _ := os.OpenFile(filename, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
	defer dstFile.Close()

	encoder := json.NewEncoder(dstFile)
	err := encoder.Encode(obj)
	if err == nil{
		fmt.Println("Success")
		return true
	}else{
		fmt.Println("Failure")
		return false}}Copy the code

You can see that three JSON files appear in the folder.

4. Optimized code

import ( "encoding/json" "fmt" "os" ) type IProduct interface { GetName() string GetPrice() float64 } type Product struct { Name string Price float64 } func (p *Product)GetName() string { return p.Name } func (p *Product)GetPrice() float64 { return p.Price } type Computer struct { //Name string //Price float64 Product Cpu string Memory int Disk int }  type Tshirt struct { //Name string //Price float64 Product Color string Size int Sex bool } type Car struct { //Name string //Price float64 Product Cap int Power string } func main() { products := make([]IProduct,0) products = Append (products, &Computer{Product{" destroy ",9.9},"i7",32,2048}) products = append(products, &tshirt {Product{" Product ",88},"Red",40,false}) products = append(products, &car {Product{"Tesla",237811},5," Tesla"}) for _,p := range products{// pValue := reflect.valueof (p) // name := pValue.FieldByName("Name").Interface() // fmt.Println(name) // EncodeObjToJsonFile(p,"E:\\ Path to blockchain \\ 01.0_GO Language foundation -v3.0\\code\\ SRC \jsonFile\\"+ name.(string) +".json") EncodeObjToJsonFile(p,"E:\\ path to blockchain palace \\ 01.0_GO Language foundation -v3.0\\code\\ SRC \\jsonFile\\"+ p.getName () +".json")}} func EncodeObjToJsonFile(obj interface{},filename string) bool { dstFile, _ := os.OpenFile(filename, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666) defer dstFile.Close() encoder := json.NewEncoder(dstFile) err := encoder.Encode(obj) if err == nil{ FMT.Println(" success ") return true}else{FMT.Println(" failure ") return false}} Package main import (" encoding/json" "FMT" "OS ")  ) type IProduct interface { GetName() string GetPrice() float64 } type Product struct { Name string Price float64 } func (p *Product)GetName() string { return p.Name } func (p *Product)GetPrice() float64 { return p.Price } type Computer  struct { //Name string //Price float64 Product Cpu string Memory int Disk int } type Tshirt struct { //Name string //Price float64 Product Color string Size int Sex bool } type Car struct { //Name string //Price float64 Product Cap int  Power string } func main() { products := make([]IProduct,0) products = append(products, &computer {Product{" Product ",9.9},"i7",32,2048}) products = append(products, &tshirt {Product{" Product ",88},"Red",40,false}) products = append(products, &car {Product{"Tesla",237811},5," Tesla"}) for _,p := range products{// pValue := reflect.valueof (p) // name := pValue.FieldByName("Name").Interface() // fmt.Println(name) // EncodeObjToJsonFile(p,"E:\\ Path to blockchain \\ 01.0_GO Language foundation -v3.0\\code\\ SRC \jsonFile\\"+ name.(string) +".json") EncodeObjToJsonFile(p,"E:\\ path to blockchain palace \\ 01.0_GO Language foundation -v3.0\\code\\ SRC \\jsonFile\\"+ p.getName () +".json")}} func EncodeObjToJsonFile(obj interface{},filename string) bool { dstFile, _ := os.OpenFile(filename, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666) defer dstFile.Close() encoder := json.NewEncoder(dstFile) err := encoder.Encode(obj) if err == nil{ Println(" success ") return true}else{FMT.Println(" failure ") return false}}Copy the code

Use of GoBench [Go Study Notes] | Go Theme month juejin.cn/post/694346…

Use of the GO Test [Go Learning Notes] | Go Theme month juejin.cn/post/694319…