Convert Figma logo to code with AI

davecgh logogo-spew

Implements a deep pretty printer for Go data structures to aid in debugging

6,039
363
6,039
64

Top Related Projects

22,996

A toolkit with common assertions and mocks that plays nicely with the standard library

24,520

Structured, pluggable logging for Go.

8,178

Simple error handling primitives

9,298

GoMock is a mocking framework for the Go programming language.

21,647

Blazing fast, structured, leveled logging in Go.

10,371

Zero Allocation JSON Logger

Quick Overview

Go-spew is a deep pretty printer for Go data structures to aid in debugging. It can print out entire data structures, including nested types, in a readable format, making it easier to visualize complex data during development and debugging processes.

Pros

  • Supports a wide range of Go data types, including custom types
  • Provides configurable output formatting options
  • Offers both standard and verbose output modes
  • Integrates well with Go's testing framework

Cons

  • Can significantly increase output size for large data structures
  • May impact performance when used extensively in production code
  • Learning curve for advanced configuration options
  • Limited customization for specific type handling

Code Examples

  1. Basic usage:
import (
    "fmt"
    "github.com/davecgh/go-spew/spew"
)

func main() {
    data := map[string]interface{}{
        "name": "John Doe",
        "age":  30,
        "hobbies": []string{
            "reading",
            "swimming",
        },
    }
    spew.Dump(data)
}
  1. Custom configuration:
import "github.com/davecgh/go-spew/spew"

func main() {
    cfg := spew.ConfigState{
        Indent:                  "  ",
        MaxDepth:                2,
        DisableMethods:          true,
        DisablePointerAddresses: true,
    }
    cfg.Dump(complexStruct)
}
  1. Using with Go's testing framework:
import (
    "testing"
    "github.com/davecgh/go-spew/spew"
)

func TestSomething(t *testing.T) {
    result := SomeFunction()
    expected := SomeExpectedValue()
    if !reflect.DeepEqual(result, expected) {
        t.Errorf("Unexpected result. Got:\n%s\nWant:\n%s", spew.Sdump(result), spew.Sdump(expected))
    }
}

Getting Started

To use go-spew in your Go project, follow these steps:

  1. Install the package:

    go get -u github.com/davecgh/go-spew/spew
    
  2. Import the package in your Go file:

    import "github.com/davecgh/go-spew/spew"
    
  3. Use the spew.Dump() function to print out your data structures:

    spew.Dump(yourDataStructure)
    

That's it! You can now use go-spew to debug and inspect your Go data structures more easily.

Competitor Comparisons

22,996

A toolkit with common assertions and mocks that plays nicely with the standard library

Pros of testify

  • Comprehensive testing toolkit with assertions, mocks, and suites
  • Widely adopted in the Go community, extensive ecosystem support
  • Provides a more expressive and readable syntax for writing tests

Cons of testify

  • Larger dependency with more code to maintain
  • May introduce complexity for simple testing scenarios
  • Learning curve for developers new to the library's features

Code Comparison

testify:

assert := assert.New(t)
assert.Equal(expected, actual, "The two values should be equal")
assert.NotNil(object, "Object should not be nil")
mock.On("Method", arg1, arg2).Return(result)

go-spew:

spew.Dump(object)
spew.Printf("%#v", object)

Summary

testify is a comprehensive testing framework offering assertions, mocks, and suites, while go-spew focuses on deep pretty printing of Go data structures. testify provides more features for writing expressive tests but may be overkill for simple scenarios. go-spew excels at debugging and inspecting complex data structures but lacks built-in testing utilities. Choose testify for robust test suites or go-spew for detailed data inspection and debugging.

24,520

Structured, pluggable logging for Go.

Pros of logrus

  • More comprehensive logging framework with structured logging support
  • Offers log levels, hooks, and formatters for advanced logging needs
  • Widely adopted in the Go community with extensive documentation

Cons of logrus

  • Heavier and more complex than go-spew for simple debugging tasks
  • May be overkill for projects that don't require advanced logging features
  • Slightly steeper learning curve compared to go-spew's straightforward API

Code Comparison

logrus:

log := logrus.New()
log.WithFields(logrus.Fields{
    "animal": "walrus",
    "size":   10,
}).Info("A group of walrus emerges from the ocean")

go-spew:

type Animal struct {
    Name string
    Size int
}
spew.Dump(Animal{Name: "walrus", Size: 10})

Summary

logrus is a feature-rich logging framework suitable for complex applications requiring structured logging and advanced features. go-spew, on the other hand, is a simpler tool focused on deep pretty-printing of Go data structures for debugging purposes. While logrus offers more flexibility and power for logging, go-spew excels in quickly visualizing complex data structures during development and debugging.

8,178

Simple error handling primitives

Pros of pkg/errors

  • Focuses on error handling and wrapping, providing more context to errors
  • Offers stack trace functionality for better debugging
  • Integrates well with standard Go error handling practices

Cons of pkg/errors

  • Limited to error handling and doesn't provide general data inspection
  • Doesn't offer pretty-printing capabilities for complex data structures
  • May add some overhead to error creation and handling

Code Comparison

pkg/errors:

err := errors.New("original error")
wrappedErr := errors.Wrap(err, "additional context")
fmt.Printf("%+v\n", wrappedErr)

go-spew:

complexData := struct {
    Name string
    Age  int
}{Name: "John", Age: 30}
spew.Dump(complexData)

Summary

pkg/errors is specialized for error handling and provides enhanced context and stack traces. go-spew, on the other hand, is a general-purpose pretty-printer and data dumper, useful for debugging complex data structures. While pkg/errors improves error management, go-spew excels at visualizing data during development. The choice between them depends on whether you need better error handling (pkg/errors) or improved data inspection (go-spew) in your Go project.

9,298

GoMock is a mocking framework for the Go programming language.

Pros of mock

  • Specifically designed for mocking in Go unit tests
  • Integrates well with Go's testing package
  • Provides a powerful and flexible mocking framework

Cons of mock

  • Steeper learning curve compared to go-spew
  • Requires more setup and configuration for each test case
  • May introduce complexity in simple test scenarios

Code Comparison

mock:

ctrl := gomock.NewController(t)
defer ctrl.Finish()

mockObj := NewMockInterface(ctrl)
mockObj.EXPECT().SomeMethod(gomock.Any()).Return(42)

// Use mockObj in tests

go-spew:

import "github.com/davecgh/go-spew/spew"

// Simply dump the object for debugging
spew.Dump(someObject)

Summary

mock is a powerful mocking framework for Go, ideal for complex unit testing scenarios. It offers more control and flexibility but requires more setup.

go-spew is a simpler tool focused on pretty-printing Go data structures, useful for quick debugging and logging. It's easier to use but lacks mocking capabilities.

Choose mock for comprehensive unit testing with mocks, and go-spew for straightforward data inspection and debugging.

21,647

Blazing fast, structured, leveled logging in Go.

Pros of zap

  • Designed for high-performance structured logging
  • Offers flexible log levels and field-based logging
  • Provides both a simple and a more advanced API for different use cases

Cons of zap

  • Steeper learning curve compared to simpler logging solutions
  • Requires more setup and configuration for optimal use
  • May be overkill for small projects or simple logging needs

Code Comparison

zap:

logger, _ := zap.NewProduction()
defer logger.Sync()
logger.Info("Failed to fetch URL",
    zap.String("url", url),
    zap.Int("attempt", 3),
    zap.Duration("backoff", time.Second),
)

go-spew:

import "github.com/davecgh/go-spew/spew"

data := SomeComplexStruct{...}
spew.Dump(data)

Key Differences

  • zap focuses on structured logging for production environments, while go-spew is primarily used for debugging and data inspection
  • zap offers more control over log formatting and output, whereas go-spew specializes in detailed data dumps
  • zap is designed for performance in high-throughput applications, while go-spew prioritizes comprehensive data representation

Use Cases

  • Use zap for application logging in production environments where performance and structured data are crucial
  • Choose go-spew for debugging complex data structures or when you need a quick and detailed view of an object's contents
10,371

Zero Allocation JSON Logger

Pros of zerolog

  • Designed for high-performance, zero-allocation JSON logging
  • Supports structured logging with a fluent API
  • Offers context-aware logging and field management

Cons of zerolog

  • Primarily focused on JSON output, less flexible for other formats
  • Steeper learning curve compared to simpler logging libraries
  • May be overkill for small projects or simple logging needs

Code comparison

zerolog:

logger := zerolog.New(os.Stdout).With().Timestamp().Logger()
logger.Info().Str("foo", "bar").Msg("Hello World")

go-spew:

spew.Dump(someComplexStruct)

Key differences

  • zerolog is a logging library, while go-spew is a deep pretty printer for Go data structures
  • zerolog focuses on structured, performant logging, while go-spew excels at debugging and data inspection
  • zerolog produces JSON output by default, while go-spew generates human-readable formatted output

Use cases

  • Use zerolog for production-grade logging in high-performance applications
  • Use go-spew for debugging, data inspection, and generating readable representations of complex data structures

Community and maintenance

  • zerolog: Active development, 7.5k+ stars, 500+ forks
  • go-spew: Stable, widely used, 5k+ stars, 400+ forks

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

go-spew

Build Status ISC License Coverage Status

Go-spew implements a deep pretty printer for Go data structures to aid in debugging. A comprehensive suite of tests with 100% test coverage is provided to ensure proper functionality. See test_coverage.txt for the gocov coverage report. Go-spew is licensed under the liberal ISC license, so it may be used in open source or commercial projects.

If you're interested in reading about how this package came to life and some of the challenges involved in providing a deep pretty printer, there is a blog post about it here.

Documentation

GoDoc

Full go doc style documentation for the project can be viewed online without installing this package by using the excellent GoDoc site here: http://godoc.org/github.com/davecgh/go-spew/spew

You can also view the documentation locally once the package is installed with the godoc tool by running godoc -http=":6060" and pointing your browser to http://localhost:6060/pkg/github.com/davecgh/go-spew/spew

Installation

$ go get -u github.com/davecgh/go-spew/spew

Quick Start

Add this import line to the file you're working in:

import "github.com/davecgh/go-spew/spew"

To dump a variable with full newlines, indentation, type, and pointer information use Dump, Fdump, or Sdump:

spew.Dump(myVar1, myVar2, ...)
spew.Fdump(someWriter, myVar1, myVar2, ...)
str := spew.Sdump(myVar1, myVar2, ...)

Alternatively, if you would prefer to use format strings with a compacted inline printing style, use the convenience wrappers Printf, Fprintf, etc with %v (most compact), %+v (adds pointer addresses), %#v (adds types), or %#+v (adds types and pointer addresses):

spew.Printf("myVar1: %v -- myVar2: %+v", myVar1, myVar2)
spew.Printf("myVar3: %#v -- myVar4: %#+v", myVar3, myVar4)
spew.Fprintf(someWriter, "myVar1: %v -- myVar2: %+v", myVar1, myVar2)
spew.Fprintf(someWriter, "myVar3: %#v -- myVar4: %#+v", myVar3, myVar4)

Debugging a Web Application Example

Here is an example of how you can use spew.Sdump() to help debug a web application. Please be sure to wrap your output using the html.EscapeString() function for safety reasons. You should also only use this debugging technique in a development environment, never in production.

package main

import (
    "fmt"
    "html"
    "net/http"

    "github.com/davecgh/go-spew/spew"
)

func handler(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "text/html")
    fmt.Fprintf(w, "Hi there, %s!", r.URL.Path[1:])
    fmt.Fprintf(w, "<!--\n" + html.EscapeString(spew.Sdump(w)) + "\n-->")
}

func main() {
    http.HandleFunc("/", handler)
    http.ListenAndServe(":8080", nil)
}

Sample Dump Output

(main.Foo) {
 unexportedField: (*main.Bar)(0xf84002e210)({
  flag: (main.Flag) flagTwo,
  data: (uintptr) <nil>
 }),
 ExportedField: (map[interface {}]interface {}) {
  (string) "one": (bool) true
 }
}
([]uint8) {
 00000000  11 12 13 14 15 16 17 18  19 1a 1b 1c 1d 1e 1f 20  |............... |
 00000010  21 22 23 24 25 26 27 28  29 2a 2b 2c 2d 2e 2f 30  |!"#$%&'()*+,-./0|
 00000020  31 32                                             |12|
}

Sample Formatter Output

Double pointer to a uint8:

	  %v: <**>5
	 %+v: <**>(0xf8400420d0->0xf8400420c8)5
	 %#v: (**uint8)5
	%#+v: (**uint8)(0xf8400420d0->0xf8400420c8)5

Pointer to circular struct with a uint8 field and a pointer to itself:

	  %v: <*>{1 <*><shown>}
	 %+v: <*>(0xf84003e260){ui8:1 c:<*>(0xf84003e260)<shown>}
	 %#v: (*main.circular){ui8:(uint8)1 c:(*main.circular)<shown>}
	%#+v: (*main.circular)(0xf84003e260){ui8:(uint8)1 c:(*main.circular)(0xf84003e260)<shown>}

Configuration Options

Configuration of spew is handled by fields in the ConfigState type. For convenience, all of the top-level functions use a global state available via the spew.Config global.

It is also possible to create a ConfigState instance that provides methods equivalent to the top-level functions. This allows concurrent configuration options. See the ConfigState documentation for more details.

* Indent
	String to use for each indentation level for Dump functions.
	It is a single space by default.  A popular alternative is "\t".

* MaxDepth
	Maximum number of levels to descend into nested data structures.
	There is no limit by default.

* DisableMethods
	Disables invocation of error and Stringer interface methods.
	Method invocation is enabled by default.

* DisablePointerMethods
	Disables invocation of error and Stringer interface methods on types
	which only accept pointer receivers from non-pointer variables.  This option
	relies on access to the unsafe package, so it will not have any effect when
	running in environments without access to the unsafe package such as Google
	App Engine or with the "safe" build tag specified.
	Pointer method invocation is enabled by default.

* DisablePointerAddresses
	DisablePointerAddresses specifies whether to disable the printing of
	pointer addresses. This is useful when diffing data structures in tests.

* DisableCapacities
	DisableCapacities specifies whether to disable the printing of capacities
	for arrays, slices, maps and channels. This is useful when diffing data
	structures in tests.

* ContinueOnMethod
	Enables recursion into types after invoking error and Stringer interface
	methods. Recursion after method invocation is disabled by default.

* SortKeys
	Specifies map keys should be sorted before being printed. Use
	this to have a more deterministic, diffable output.  Note that
	only native types (bool, int, uint, floats, uintptr and string)
	and types which implement error or Stringer interfaces are supported,
	with other types sorted according to the reflect.Value.String() output
	which guarantees display stability.  Natural map order is used by
	default.

* SpewKeys
	SpewKeys specifies that, as a last resort attempt, map keys should be
	spewed to strings and sorted by those strings.  This is only considered
	if SortKeys is true.

Unsafe Package Dependency

This package relies on the unsafe package to perform some of the more advanced features, however it also supports a "limited" mode which allows it to work in environments where the unsafe package is not available. By default, it will operate in this mode on Google App Engine and when compiled with GopherJS. The "safe" build tag may also be specified to force the package to build without using the unsafe package.

License

Go-spew is licensed under the copyfree ISC License.