Skip to content

Inlined interfaces #531

@nikolaydubina

Description

@nikolaydubina

Description

Purpose

Avoid declaring non exported upstream interfaces as separate types just so they can be mocked.

Details

https://go.dev/play/p/Bt74sBt01Yl

package main

import "fmt"

// go generate mockery Employee.address

// struct with interface
type Employee struct {
	address interface {
		StreetName() string
		BlockNumber() int
	}
}

// constructor with inlined interface
func NewEmployee(
	address interface {
		StreetName() string
		BlockNumber() int
	},
) Employee {
	return Employee{address: address}
}

// concerete upstream
type HumanAddress struct {
	streetName  string
	blockNumber int
}

func (h HumanAddress) StreetName() string { return h.streetName }

func (h HumanAddress) BlockNumber() int { return h.blockNumber }

func main() {
	e := NewEmployee(HumanAddress{streetName: "some-street", blockNumber: 11})
	fmt.Printf("%#v", e)
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions