github.com/shogo82148/std@v1.22.1-0.20240327122250-4e474527810c/encoding/gob/example_interface_test.go (about)

     1  // Copyright 2013 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package gob_test
     6  
     7  import (
     8  	"github.com/shogo82148/std/bytes"
     9  	"github.com/shogo82148/std/encoding/gob"
    10  	"github.com/shogo82148/std/fmt"
    11  )
    12  
    13  // この例では、インターフェース値のエンコード方法を示します。通常の型との主な違いは、
    14  // インターフェースを実装する具体的な型を登録することです。
    15  func Example_interface() {
    16  	var network bytes.Buffer // ネットワークの代わり。
    17  
    18  	// エンコーダとデコーダ(通常はエンコーダとは別のマシン上)に具体的な型を登録する必要があります。
    19  	// それぞれの端では、これがどの具体的な型がインターフェースを実装して送信されているかをエンジンに伝えます。
    20  	gob.Register(Point{})
    21  
    22  	// エンコーダを作成し、いくつかの値を送信します。
    23  	enc := gob.NewEncoder(&network)
    24  	for i := 1; i <= 3; i++ {
    25  		interfaceEncode(enc, Point{3 * i, 4 * i})
    26  	}
    27  
    28  	// デコーダを作成し、いくつかの値を受信します。
    29  	dec := gob.NewDecoder(&network)
    30  	for i := 1; i <= 3; i++ {
    31  		result := interfaceDecode(dec)
    32  		fmt.Println(result.Hypotenuse())
    33  	}
    34  
    35  	// Output:
    36  	// 5
    37  	// 10
    38  	// 15
    39  }