PHpullh
학습 라이브러리/Go/의존성 주입

GO · 구조체/인터페이스

의존성 주입

인터페이스를 통해 의존성을 주입하여 테스트 가능하고 유연한 코드를 작성합니다.

구조체/인터페이스고급dependency-injectioninterfacetestabledecoupling

핵심 설명

인터페이스를 통해 의존성을 주입하여 테스트 가능하고 유연한 코드를 작성합니다.

Go code

package main

import "fmt"

// 인터페이스 정의
type UserRepo interface {
	FindByID(id int) (string, error)
}

type Mailer interface {
	Send(to, subject string) error
}

// 서비스: 의존성 주입
type UserService struct {
	repo   UserRepo
	mailer Mailer
}

func NewUserService(r UserRepo, m Mailer) *UserService {
	return &UserService{repo: r, mailer: m}
}

func (s *UserService) Greet(id int) error {
	name, err := s.repo.FindByID(id)
	if err != nil { return err }
	return s.mailer.Send(name, "환영합니다!")
}

// 구현체
type MemoryRepo struct{ users map[int]string }
func (r *MemoryRepo) FindByID(id int) (string, error) {
	if u, ok := r.users[id]; ok { return u, nil }
	return "", fmt.Errorf("사용자 없음: %d", id)
}

type ConsoleMailer struct{}
func (m *ConsoleMailer) Send(to, subj string) error {
	fmt.Printf("메일 → %s: %s\n", to, subj)
	return nil
}

func main() {
	repo := &MemoryRepo{users: map[int]string{1: "Gopher"}}
	svc := NewUserService(repo, &ConsoleMailer{})
	svc.Greet(1)
}

학습 팁

생성자에서 인터페이스를 받으면 테스트 시 목(mock) 객체를 쉽게 주입할 수 있습니다.

주의할 점

구체적인 타입에 의존하면 테스트와 교체가 어렵습니다. 항상 인터페이스에 의존하세요.

자주 묻는 질문

의존성 주입란 무엇인가요?

인터페이스를 통해 의존성을 주입하여 테스트 가능하고 유연한 코드를 작성합니다.

의존성 주입 학습 시 주의할 점은 무엇인가요?

구체적인 타입에 의존하면 테스트와 교체가 어렵습니다. 항상 인터페이스에 의존하세요.