Created
January 26, 2015 01:54
-
-
Save ota42y/1c4063a5fd988dbaaa74 to your computer and use it in GitHub Desktop.
goの継承テスト
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import "fmt" | |
type If interface{ // PrintDataメソッドを持つインターフェースを定義 | |
PrintData() | |
} | |
type MyBase struct { | |
Count int | |
} | |
type SubStruct struct { | |
*MyBase//埋め込む | |
A int | |
} | |
func (s SubStruct) PrintData() { // SubStructにPrintDataを実装 | |
fmt.Printf("%v\n", s.A) | |
} | |
func main() { | |
var m []MyBase | |
base := MyBase{Count: 1} | |
m = append(m, base) // 基底クラスは追加できる | |
s := SubStruct{MyBase: &MyBase{Count:2}, A: 42} // 継承(っぽい事を)したクラス | |
// m = append(m, s) // 追加できない | |
fmt.Printf("%v\n", s.Count) // 基底クラスの変数に直接アクセス可能 | |
// x := s.(MyBase) // ダウンキャスト不可 | |
//fmt.Printf("%v\n", x.Count) | |
var ifArray []If // インターフェースの配列 | |
ifArray = append(ifArray, s) // インターフェースを実装していれば入れられる | |
ifArray[0].PrintData() // もちろん呼べる | |
// fmt.Printf("%v\n", ifArray[0].Count) // インターフェースのままではアクセスできない | |
z := ifArray[0].(SubStruct) | |
fmt.Printf("%v\n", z.Count) // インターフェースならダウンキャストも可能 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment