Go の implicit implementation は structural typing です。TypeScript の type compatibility と、Python の Protocol と同じで、要求された signature が concrete type にあれば assignable です。interface を継承したとは書きません。
| 包含の対象 | interface の名指し | |
|---|---|---|
| Go | method set | しない |
| TypeScript | property(field と method) | implements は任意。assignability には不要 |
Python Protocol | method | 継承は任意。判定は type checker |
| C# の implicit implementation | public method が interface member と一致 | : IStringer が必要 |
TypeScript と Protocol
interface Stringer {
string(): string
}
const user = { string: () => "Go" }
const s: Stringer = user
user は Stringer を implements していません。property の形が一致するので代入できます。class に implements Stringer と書くと、その class 宣言の時点で不足が compile error になります。書かなくても、object は Stringer に assignable です。field もこの形に含まれます。
class Stringer(Protocol):
def string(self) -> str: ...
class User:
def string(self) -> str:
return "Go"
User は Stringer を継承していません。mypy などの type checker が signature を比較します。実行時の Python はこの包含を検査しません。
C# の implicit implementation
C# で implicit implementation と呼ぶものは、method を interface 名で修飾しない書き方です。class が interface を列挙する宣言は残ります。
interface IStringer {
string String();
}
class User : IStringer {
public string String() => "Go";
}
: IStringer を消すと、String() があっても User は IStringer に代入できません。nominal typing です。
Go は method set
type Stringer interface{ String() string }
type User struct{ Name string }
func (u User) String() string { return u.Name }
func main() {
var s Stringer = User{Name: "Go"}
fmt.Println(s.String()) // Go
}
比較するのは method の名前と signature です。field は見ません。String() string が User の method set にあれば、User は Stringer に assignable です。この判定は言語の assignability で、代入を compile するときに行われます。
pointer receiver の method は *T の method set にしか入りません。T の値は、その method を要求する interface に代入できません。
concrete type が interface 名を持たないので、実装側の package はその interface の package を import しません。Read([]byte) (int, error) を持つ型は、io を import した呼び出し側で io.Reader に代入できます。
宣言の位置で検査を固定するときは、blank identifier へ代入します。代入は実行されません。
var _ Stringer = User{}
var _ io.Reader = (*bufio.Reader)(nil)