author
Kevin Kelche

How to print structs in Go


How to print structs in Go

To print structs we use the fmt package i.e fmt.Printf(ā€œ%vā€, structName). This will print the struct in the format of a map. To print the struct in a more readable format we use the %#v format specifier. This will print the struct in the format of a struct.

main.go
package main

import "fmt"

type Mystruct struct {
    Name string
    Age  int
}

func main()  {
    myStruct := Mystruct{
        Name: "John",
        Age:  20,
    }

    fmt.Printf("%v", myStruct)
    fmt.Printf("%#v", myStruct)
}

Copied!

Output:

output
{John 20}

main.Mystruct{Name:"John", Age:20}

Copied!

we can also convert the struct to JSON and then print the elements of the struct

main.go
package main

import (
    "encoding/json"
    "fmt"
)

type Mystruct struct {
    Name string
    Age  int
}


func main()  {
    myStruct := Mystruct{
        Name: "John",
        Age:  20,
    }

    json, err := json.Marshal(myStruct)
    if err != nil {
        fmt.Println(err)
    }

    fmt.Println(string(json))
}

Copied!

Output:

output
{"Name":"John","Age":20}

Copied!

How to print a nested struct in Go

To print a nested struct we use the %#v format specifier. This will print the struct in the format of a struct.

main.go
package main

import "fmt"

type Mystruct struct {
    Name string
    Age  int
}

type Mystruct2 struct {
    Name string
    Age  int
    Mystruct
}

func main()  {
    myStruct := Mystruct2{
        Name: "John",
        Age:  20,
        Mystruct: Mystruct{
            Name: "John",
            Age:  20,
        },
    }

    fmt.Printf("%#v", myStruct)

Copied!

Output:

output
main.Mystruct2{Name:"John", Age:20, Mystruct:main.Mystruct{Name:"John", Age:20}}

Copied!

How to print a struct with a slice in Go

To print a struct with a slice we use the %#v format specifier. This will print the struct in the format of a struct.

main.go
package main

import "fmt"

type Mystruct struct {
    Name string
    Age  int
}

type Mystruct2 struct {
    Name string
    Age  int
    Mystruct
    MySlice []string
}


func main()  {
    myStruct := Mystruct2{
        Name: "John",
        Age:  20,
        Mystruct: Mystruct{
            Name: "John",
            Age:  20,
        },
        MySlice: []string{"one", "two"},
    }

    fmt.Printf("%#v", myStruct)
}

Copied!

Output:

output
main.Mystruct2{Name:"John", Age:20, Mystruct:main.Mystruct{Name:"John", Age:20}, MySlice:[]string{"one", "two"}}

Copied!

Subscribe to my newsletter

Get the latest posts delivered right to your inbox.