Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix pointer implement interface #2

Merged
merged 2 commits into from
Jan 28, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 17 additions & 2 deletions container.go
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,7 @@ func (container Container) fill(c component) {
}

for i := range c.dependencies {
ptrInterface := false
dep := c.dependencies[i]
cdep := component{}

Expand All @@ -210,8 +211,22 @@ func (container Container) fill(c component) {
for _, gr := range container.components {
ctyp := gr[0].value.Type()

if ctyp.Implements(dep.typ) && (dep.impl == "" || dep.impl == ctyp.Name()) {
if dep.impl != "" && dep.impl != ctyp.Name() {
continue
}

if ctyp.Implements(dep.typ) {
if fcedp, ok := gr.find(dep.id); ok {
cdep = fcedp
matches++
continue
}
}

// scan pointer type
if reflect.PtrTo(ctyp).Implements(dep.typ) {
if fcedp, ok := gr.find(dep.id); ok {
ptrInterface = true
cdep = fcedp
matches++
}
Expand All @@ -229,7 +244,7 @@ func (container Container) fill(c component) {
container.fill(cdep)

fv := c.value.Field(dep.index)
if fv.Kind() == reflect.Ptr {
if fv.Kind() == reflect.Ptr || ptrInterface {
if !cdep.value.CanAddr() {
panic(requiresPointerError{component: c, dependency: dep, depComponent: cdep})
}
Expand Down
11 changes: 10 additions & 1 deletion wire_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,10 @@ type Valuer interface {
Value() string
}

type Setter interface {
Set(string)
}

type ComponentA struct {
Value1 string
Value2 int
Expand All @@ -21,6 +25,10 @@ func (c ComponentA) Value() string {
return c.Value1
}

func (c *ComponentA) Set(v string) {
c.Value1 = v
}

type ComponentB struct {
Value1 []int
Value2 ComponentA `wire:"hello"`
Expand All @@ -47,6 +55,7 @@ func (c ComponentD) Value() string {

type ComponentE struct {
Value1 Valuer `wire:""`
Value2 Setter `wire:""`
}

func TestWire(t *testing.T) {
Expand Down Expand Up @@ -111,7 +120,7 @@ func TestWire(t *testing.T) {

assert.Equal(t, ComponentD{Value1: "LGTM!"}, componentD)

assert.Equal(t, ComponentE{Value1: ComponentA{Value1: "Hi!", Value2: 10}}, componentE)
assert.Equal(t, ComponentE{Value1: ComponentA{Value1: "Hi!", Value2: 10}, Value2: &ComponentA{Value1: "Hi!", Value2: 10}}, componentE)

assert.Equal(t, "LGTM!", resolvedString)
assert.Equal(t, true, resolvedBool)
Expand Down