埋め込みは合成
Coddyの「C++開発者のためのGo」コースのレッスン 29/48。
C++の仮想継承とオーバーライドに直接対応するGoのクラス機能はありません。Goの埋め込みはメンバーを昇格させますが、埋め込まれたレシーバーから外側のレシーバーへ戻る仮想ディスパッチではありません。置換可能性にはインターフェースを、実装の再利用には明示的な委譲を使います。
埋め込みは、内包された値を通じてフィールドとメソッドを昇格させるものであり、クラス継承ではありません。それでも埋め込まれたフィールドを明示的に指定できます。昇格されたメソッドは宣言時のレシーバーを使うため、埋め込みによってそのメソッド内に仮想オーバーライドが生じることはありません。
C++の例
#include <algorithm>
#include <iomanip>
#include <iostream>
#include <map>
#include <numeric>
#include <stdexcept>
#include <string>
#include <utility>
#include <vector>
int main() {
struct Base {
virtual std::string label() const { return "base"; }
virtual ~Base() = default;
};
struct Child : Base {
std::string label() const override { return Base::label() + "!"; }
};
Child child;
Base& base = child;
std::cout << base.label() << '\n';
}ソースコードの出力:
base!Goの例
package main
import ("fmt")
type Position struct { X int }; type Window struct { Position; Width int }
func main(){w:=Window{Position:Position{X:4},Width:8}
fmt.Println(w.X,w.Position.X)}Goの出力:
4 4チャレンジ
簡単Person{Name string}を定義し、MemberにはPersonを埋め込み、Role stringを追加します。Member.Label()はName + コロン + Roleを返します。Solveはロールとしてeditorを使用します。
宣言済みのAPIを実装し、結果を出力せずに返してください。ドライバーは必要なAPIを確認し、呼び出し元の入力を保持します。コレクションの標準出力にはJSONではなく、Goの角括弧形式が使われます。
コードはperson.go、member.go、exercise.goに記述します。main.goには提供された入出力コードがあり、編集できません。フラットなpackage mainを1つだけにし、2つ目のmainは追加しないでください。
自分で試してみよう
package main
import ("fmt";"strings";"strconv";"bufio";"os")
var input []string
func L(i int)string{if i<len(input){return input[i]};return ""}
func I(i int)int{n,e:=strconv.Atoi(L(i));if e!=nil{panic(e)};return n}
func Ints(i int)[]int{out:=[]int{};if L(i)==""{return out};for _,s:=range strings.Split(L(i),","){n,e:=strconv.Atoi(s);if e!=nil{panic(e)};out=append(out,n)};return out}
func Words(i int)[]string{if L(i)==""{return []string{}};return strings.Split(L(i),",")}
func must(ok bool,message string){if !ok{panic("API: "+message)}}
func main(){
scanner:=bufio.NewScanner(os.Stdin);for scanner.Scan(){input=append(input,scanner.Text())};if scanner.Err()!=nil{panic(scanner.Err())}
a0:=L(0); before0:=fmt.Sprint(a0)
must((Member{Person:Person{Name:"A"},Role:"owner"}).Label()=="A:owner","embedded API");
result:=Solve(a0)
must(fmt.Sprint(a0)==before0,"input mutation")
fmt.Println(result)
}
このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。
C++開発者のためのGoのすべてのレッスン
自分で練習してみよう: Goオンラインコンパイラ