Skip to content

Setting: default

default [PACKAGE:]FUNC

default [PACKAGE:]FUNC can be defined as method comment.

By default the target object is initialized with zero values | Go docs. With default you can instruct Goverter to use FUNC as default target value or constructor for the target value.

The FUNC may have the signatures described in Signature: Optional Source.

You can optionally define the PACKAGE where FUNC is located by separating the PACKAGE and FUNC with a :(colon). If no package is defined, then the package of the conversion method is used.

go
package example

// goverter:converter
type Converter interface {
	// goverter:default NewOutput
	Convert(*Input) *Output
}

type Input struct {
	Age  int
	Name *string
}
type Output struct {
	Age  int
	Name *string
}

func NewOutput() *Output {
	name := "jmattheis"
	return &Output{Age: 42, Name: &name}
}
go
// Code generated by github.com/jmattheis/goverter, DO NOT EDIT.
//go:build !goverter

package generated

import default1 "github.com/jmattheis/goverter/example/default"

type ConverterImpl struct{}

func (c *ConverterImpl) Convert(source *default1.Input) *default1.Output {
	pExampleOutput := default1.NewOutput()
	if source != nil {
		var exampleOutput default1.Output
		exampleOutput.Age = (*source).Age
		if (*source).Name != nil {
			xstring := *(*source).Name
			exampleOutput.Name = &xstring
		}
		pExampleOutput = &exampleOutput
	}
	return pExampleOutput
}

default:update [yes|no]

default:update [yes,no] is a boolean setting and can be defined as CLI argument, conversion comment or method comment. This setting is inheritable.

WARNING

If enabled, goverter requires you to return a non nil value in the default FUNC.

If enabled goverter will update the existing instance returned by the default FUNC.

go
package example

// goverter:converter
// goverter:default:update
type Converter interface {
	// goverter:default NewOutput
	Convert(*Input) *Output
}

type Input struct {
	Age  int
	Name *string
}
type Output struct {
	Age  int
	Name *string
}

func NewOutput() *Output {
	name := "jmattheis"
	return &Output{Age: 42, Name: &name}
}
go
// Code generated by github.com/jmattheis/goverter, DO NOT EDIT.
//go:build !goverter

package generated

import defaultupdate "github.com/jmattheis/goverter/example/default-update"

type ConverterImpl struct{}

func (c *ConverterImpl) Convert(source *defaultupdate.Input) *defaultupdate.Output {
	pExampleOutput := defaultupdate.NewOutput()
	if source != nil {
		(*pExampleOutput).Age = (*source).Age
		if (*source).Name != nil {
			xstring := *(*source).Name
			(*pExampleOutput).Name = &xstring
		}
	}
	return pExampleOutput
}