Golang 組み込み構造体へのキャスト方法(Goのポリモーフィズムの実現)
- Golangで組み込み構造体(親)へのキャストを行いたい場合は(ポリモーフィズムを得るためには)、インターフェイスの実装が必要
- 子から親への参照はある
- インターフェースの名前はGolangでは
er
が慣例
package main
import "fmt"
type Parent struct {
Attr1 string
}
type Parenter interface {
GetParent() Parent
}
type Child struct {
Parent //embed
Attr string
}
func (c Child) GetParent() Parent {
return c.Parent
}
func setf(p Parenter) {
fmt.Println(p)
}
func main() {
var ch Child
ch.Attr = "1"
ch.Attr1 = "2"
setf(ch)
}
// result
{{2} 1}
参考
あなたは、継承を使ったオブジェクト指向のデザインパターンを使おうとしています。これはGoでのやり方ではありません。また、Javaや同等のオブジェクト指向言語では、インターフェース名は’able’で終わります。Goでは、インターフェイス名は’er’で終わるのが慣例です。 You are trying to use an object oriented design pattern with inheritance. This is not how to do this in Go. Beside, interface names end in ‘able’ in Java or equivalent object oriented languages. In Go the convention is to end interface names with ’er’.
Go には型付けも継承もありません。Goは共分散や逆分散をサポートせず、その型システムには名前付き型のための階層がない。 インターフェイスを書いて、“setf “引数の型をそのインターフェイスとして設定します。これは、Goからポリモーフィズムを得る唯一の方法です。 There is no typecasting or inheritance in Go. Go doesn’t support covariance or contra variance and its type system has no hierarchy for named types. Write an interface and set “setf” argument type as that interface.It is the only way you’ll get some polymorphism out of Go. whatever you are used to in other statically typed languages such as Java doesn’t exist with Go type system.