Quick actions

cmd+k|ctrl+k

Navigation

Languages

Package fmt / Stringer interface / Essential Go

Snippet info

Language

Go

Visibility

public

Author

kkowalczyk

Created

2019-10-04T18:08:39Z

Updated

2019-10-04T18:08:39Z

package main

import (
    "fmt"
)

type User1 struct {
    Name  string
    Email string
}

type User2 struct {
    Name  string
    Email string
}

// String satisfies the fmt.Stringer interface
// Defining it on type User2 makes it available on *User2 as well
func (u User2) String() string {
    return fmt.Sprintf("%s <%s>", u.Name, u.Email)
}

func main() {
    u1 := &User1{
        Name:  "John Doe",
        Email: "[email protected]",
    }

    fmt.Printf("u1: type: %T, value: %s\n\n", u1, u1)

    u2 := User2{
        Name:  "John Doe",
        Email: "[email protected]",
    }

    fmt.Printf("u2: type:  %T, value: %s\n\n", u2, u2)

		// method define on type User2 is also available on type *User2
    u3 := &User2{
        Name:  "John Doe",
        Email: "[email protected]",
    }

    fmt.Printf("u3: type: %T, value: %s\n", u3, u3)

}
INFO