gostring

package
v1.2.0-alpha.6 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 13, 2016 License: BSD-3-Clause, Apache-2.0 Imports: 5 Imported by: 0

Documentation

Overview

The gostring plugin generates a GoString method for each message. The GoString method is called whenever you use a fmt.Printf as such:

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

or whenever you actually call GoString() The output produced by the GoString method can be copied from the output into code and used to set a variable. It is totally valid Go Code and is populated exactly as the struct that was printed out.

It is enabled by the following extensions:

  • gostring
  • gostring_all

The gostring plugin also generates a test given it is enabled using one of the following extensions:

  • testgen
  • testgen_all

Let us look at:

github.com/gogo/protobuf/test/example/example.proto

Btw all the output can be seen at:

github.com/gogo/protobuf/test/example/*

The following message:

  option (gogoproto.gostring_all) = true;

  message A {
	optional string Description = 1 [(gogoproto.nullable) = false];
	optional int64 Number = 2 [(gogoproto.nullable) = false];
	optional bytes Id = 3 [(gogoproto.customtype) = "github.com/gogo/protobuf/test/custom.Uuid", (gogoproto.nullable) = false];
  }

given to the gostring plugin, will generate the following code:

  func (this *A) GoString() string {
	if this == nil {
		return "nil"
	}
	s := strings1.Join([]string{`&test.A{` + `Description:` + fmt1.Sprintf("%#v", this.Description), `Number:` + fmt1.Sprintf("%#v", this.Number), `Id:` + fmt1.Sprintf("%#v", this.Id), `XXX_unrecognized:` + fmt1.Sprintf("%#v", this.XXX_unrecognized) + `}`}, ", ")
	return s
  }

and the following test code:

func TestAGoString(t *testing6.T) {
	popr := math_rand6.New(math_rand6.NewSource(time6.Now().UnixNano()))
	p := NewPopulatedA(popr, false)
	s1 := p.GoString()
	s2 := fmt2.Sprintf("%#v", p)
	if s1 != s2 {
		t.Fatalf("GoString want %v got %v", s1, s2)
	}
	_, err := go_parser.ParseExpr(s1)
	if err != nil {
		panic(err)
	}
}

Typically fmt.Printf("%#v") will stop to print when it reaches a pointer and not print their values, while the generated GoString method will always print all values, recursively.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func NewGoString

func NewGoString() *gostring

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL