Your cart is currently empty!
Golang: Printing Struct
Say we have a struct like this:
type Employee struct { Name string Age int Job string }
Then in your main function you have:
func main() { emp1 := Employee{ Name: "Anton", Age: "28", Job: "Cashier" } }
Printing the struct using print function:
fmt.Println(emp1) => {Anton 28 Cashier} fmt.Printf("%v\n", emp1) => {Anton 28 Cashier} fmt.Printf("%+v\n", emp1) => {Name:Anton Age:28 Job:Cashier} fmt.Printf("%#v\n", emp1) => main.Employee{Name:"Anton", Age:28, Job:"Cashier"}
Printing the struct using json.MarshalIndent function:
func MarshalIndent(v any, prefix, indent string) ([]byte, error) {}
// myStruct is an array of bytes ([]byte) // V myStruct, err := json.MarshalIndent(emp1, "", "\t") // we need to cast myStruct from []byte to string // V fmt.Println("Print struct:", string(myStruct)) => Print struct: { "Name": "Anton", "Age": 28, "Job": "Cashier" }
References:
Leave a Reply