어떻게 (콘솔에서) 인쇄 할 수 있습니다 Id, Title, Name, 등 Golang이 구조체의?
type Project struct {
    Id      int64   `json:"project_id"`
    Title   string  `json:"title"`
    Name    string  `json:"name"`
    Data    Data    `json:"data"`
    Commits Commits `json:"commits"`
}
답변
구조체에서 필드의 이름을 인쇄하려면 :
fmt.Printf("%+v\n", yourProject)
로부터 fmt패키지 :
구조체를 인쇄 할 때 더하기 플래그 (
%+v)는 필드 이름을 추가합니다.
즉, ‘ yourProject‘ 의 Project 인스턴스가 있다고 가정합니다.
JSON 및 Go 기사에서는 JSON 구조체에서 값을 검색하는 방법에 대해 자세히 설명합니다.
이 Go by 예제 페이지 는 다른 기술을 제공합니다.
type Response2 struct {
  Page   int      `json:"page"`
  Fruits []string `json:"fruits"`
}
res2D := &Response2{
    Page:   1,
    Fruits: []string{"apple", "peach", "pear"}}
res2B, _ := json.Marshal(res2D)
fmt.Println(string(res2B))
다음과 같이 인쇄됩니다.
{"page":1,"fruits":["apple","peach","pear"]}
인스턴스가없는 경우이 예제 와 같이 리플렉션 을 사용 하여 주어진 구조체의 필드 이름을 표시 해야합니다 .
type T struct {
    A int
    B string
}
t := T{23, "skidoo"}
s := reflect.ValueOf(&t).Elem()
typeOfT := s.Type()
for i := 0; i < s.NumField(); i++ {
    f := s.Field(i)
    fmt.Printf("%d: %s %s = %v\n", i,
        typeOfT.Field(i).Name, f.Type(), f.Interface())
}
답변
github “go 디버깅을 돕기 위해 Go 데이터 구조를위한 깊고 예쁜 프린터 구현”에 따르면 go-spew 를 추천하고 싶습니다.
go get -u github.com/davecgh/go-spew/spew
사용 예 :
package main
import (
    "github.com/davecgh/go-spew/spew"
)
type Project struct {
    Id      int64  `json:"project_id"`
    Title   string `json:"title"`
    Name    string `json:"name"`
    Data    string `json:"data"`
    Commits string `json:"commits"`
}
func main() {
    o := Project{Name: "hello", Title: "world"}
    spew.Dump(o)
}
산출:
(main.Project) {
 Id: (int64) 0,
 Title: (string) (len=5) "world",
 Name: (string) (len=5) "hello",
 Data: (string) "",
 Commits: (string) ""
}
답변
내 2cents는 사용하는 것이 좋을 것 json.MarshalIndent입니다. 이것이 가장 간단하기 때문에 이것이 제안되지 않은 것에 놀랐습니다. 예를 들면 다음과 같습니다.
func prettyPrint(i interface{}) string {
    s, _ := json.MarshalIndent(i, "", "\t")
    return string(s)
}
외부 뎁스가 없어서 형식이 좋은 출력물이됩니다.
답변
형식화 된 출력을 원하는 경우 사용자 지정 stringer를 구현하는 것이 좋습니다. struct
예를 들어
package main
    import "fmt"
    type Project struct {
        Id int64 `json:"project_id"`
        Title string `json:"title"`
        Name string `json:"name"`
    }
    func (p Project) String() string {
        return fmt.Sprintf("{Id:%d, Title:%s, Name:%s}", p.Id, p.Title, p.Name)
    }
    func main() {
        o := Project{Id: 4, Name: "hello", Title: "world"}
        fmt.Printf("%+v\n", o)
    }
답변
p = Project{...}
fmt.Printf("%+v", p)
fmt.Printf("%#v", p) //with type
답변
또는이 기능을 사용해보십시오 PrettyPrint()
// print the contents of the obj
func PrettyPrint(data interface{}) {
    var p []byte
    //    var err := error
    p, err := json.MarshalIndent(data, "", "\t")
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Printf("%s \n", p)
}
이것을 사용하기 위해 당신은의를 제외하고 추가 패키지를 필요하지 않습니다 fmt및 encoding/json단지 참조, 포인터, 또는 사용자가 만든 구조체의 문자.
구조체를 사용하려면 기본 또는 패키지에 초기화하고 전달하십시오 PrettyPrint().
type Prefix struct {
    Network string
    Mask    int
}
func valueStruct() {
    // struct as a value
    var nw Prefix
    nw.Network = "10.1.1.0"
    nw.Mask = 24
    fmt.Println("### struct as a pointer ###")
    PrettyPrint(&nw)
}
출력은
### struct as a pointer ###
{
    "Network": "10.1.1.0",
    "Mask": 24
} 
여기 코드를 가지고 놀아 라 .
답변
나는 쓰레기를 좋아한다 .
그들의 readme에서 :
type Person struct {
  Name   string
  Age    int
  Parent *Person
}
litter.Dump(Person{
  Name:   "Bob",
  Age:    20,
  Parent: &Person{
    Name: "Jane",
    Age:  50,
  },
})
Sdump 테스트에 매우 편리합니다. 
func TestSearch(t *testing.T) {
  result := DoSearch()
  actual := litterOpts.Sdump(result)
  expected, err := ioutil.ReadFile("testdata.txt")
  if err != nil {
    // First run, write test data since it doesn't exist
        if !os.IsNotExist(err) {
      t.Error(err)
    }
    ioutil.Write("testdata.txt", actual, 0644)
    actual = expected
  }
  if expected != actual {
    t.Errorf("Expected %s, got %s", expected, actual)
  }
}