[Go] Embedding

Jiwoo Kim·2021년 11월 11일
0

Go

목록 보기
11/11

interface

type ReadWriter interface {
    Reader
    Writer
}

인터페이스는 인터페이스만 내장할 수 있다.

struct

type ReadWriter struct {
    reader *Reader
    writer *Writer
}

구조체는 인터페이스와 구조체를 내장할 수 있다.
인터페이스는 구조체 정의할 때 구현해야 하며, 필드는 유효한 구조체 포인터로 초기화해야 한다.

유의점

There's an important way in which embedding differs from subclassing. When we embed a type, the methods of that type become methods of the outer type, but when they are invoked the receiver of the method is the inner type, not the outer one. In our example, when the Read method of a bufio.ReadWriter is invoked, it has exactly the same effect as the forwarding method written out above; the receiver is the reader field of the ReadWriter, not the ReadWriter itself.

→ outer type에서 inner type의 메서드를 invoke하면, outer type 자체가 그 메서드를 가지고 실행하는 것이 아니라 inner type에 있는 메서드에 파라미터를 forwarding해서 실행하는 것이다.

Embedding types introduces the problem of name conflicts but the rules to resolve them are simple. First, a field or method X hides any other item X in a more deeply nested part of the type. If log.Logger contained a field or method called Command, the Command field of Job would dominate it.

→ 동일한 이름의 메서드가 embedded type에 있을 때, outer type의 메서드가 호출되고 more deeply nested part of the type은 무시된다.

Second, if the same name appears at the same nesting level, it is usually an error; it would be erroneous to embed log.Logger if the Job struct contained another field or method called Logger. However, if the duplicate name is never mentioned in the program outside the type definition, it is OK. This qualification provides some protection against changes made to types embedded from outside; there is no problem if a field is added that conflicts with another field in another subtype if neither field is ever used.

→ 같은 nesting level에 있는 메서드나 필드가 이름이 겹치는 경우, type definition 밖에서 그 값이 호출되는 시점에 에러가 발생한다.

🧐 type definition level에서 protection/validation이 적용되지 않는 이유는 뭐지?

0개의 댓글