Custom Search

Thursday, September 15, 2016

Go Golang Pretty Print struct, map, slice, array

package main

/* https://golang.org/pkg/fmt/ */
import (
"encoding/json"
"fmt"
)

/*A struct is a type which contains named fields.
Define new type named 'Person'*/
type Person struct {
Name    string
Age     int
Hobbies []string
}




func main() {

/*initialize a struct.
 Create an instance of type 'Person'*/
p1 := &Person{"Sam", 20, []string{"cricket", "football"}}
/*p1 := &Person{name: "Sam", age: 20, hobbies: []string{"cricket", "football"}}*/

p1_json, _ := json.Marshal(p1)
fmt.Println("==p1_json==", string(p1_json))

p1_json_ind, _ := json.MarshalIndent(p1, "", "  ")
fmt.Println("==p1_json_ind==", string(p1_json_ind))

/*With type and field name*/
/* %#v a Go-syntax representation of the value*/
fmt.Printf("==p1==%#v \n", p1)

/*MAP*/
mapD := map[string]int{"apple": 5, "lettuce": 7}
mapB, _ := json.MarshalIndent(mapD, "", " ")
fmt.Println("==mapD==", string(mapB))
fmt.Printf("==map==%#v \n", mapD)

/*SLICE*/
/*https://blog.golang.org/go-slices-usage-and-internals
 https://blog.golang.org/slices*/
slcD := []string{"apple", "peach", "pear"}
slcB, _ := json.MarshalIndent(slcD, "", " ")
fmt.Println("==slice==", string(slcB))
fmt.Printf("==slice=%#v \n", slcB)

}

1 comment: