Skip to content

The Setter interface only works on struct pointer fields, not the struct itself #16

@mattalexander-pantheon

Description

@mattalexander-pantheon
package test

import (
	"github.com/creasty/defaults"
	"testing"
)

type Main struct {
	MainInt int `default:"-"`
	*Other  `default:"{}"`
}

type Other struct {
	OtherInt int `default:"-"`
}

func (s *Main) SetDefaults() {
	if defaults.CanUpdate(s.MainInt) {
		s.MainInt = 1
	}
}

func (s *Other) SetDefaults() {
	if defaults.CanUpdate(s.OtherInt) {
		s.OtherInt = 1
	}
}

func TestDefaultsSetter(t *testing.T) {
	main := &Main{}
	defaults.Set(main)
	if main.OtherInt != 1 {
		t.Errorf("expected 1 for OtherInt, got %d", main.OtherInt)
	}
	if main.MainInt != 1 {
		t.Errorf("expected 1 for MainInt, got %d", main.MainInt)
	}
}

Which outputs:

=== RUN   TestDefaultsSetter
    TestDefaultsSetter: dev_test.go:36: expected 1 for MainInt, got 0
--- FAIL: TestDefaultsSetter (0.00s)
FAIL

Process finished with exit code 1

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions