LoginSignup
0
1

More than 5 years have passed since last update.

Goの埋め込みstructはキャストできない

Last updated at Posted at 2019-02-19
package main

import "fmt"

type Hoge struct {
    m string
}

type Fuga struct {
    Hoge
}

func main() {
    h := Hoge{"hogehoge"}
    f := Fuga{Hoge: h}

    fmt.Println(f)
}

実行結果

{{hogehoge}}

FugaはHoge->mを直下のメンバーのように呼び出せるけど実際は入れ子の状態で格納されている

fmt.Println(f.m) // out: "hogehoge"
fmt.Println(f.Hoge.m) // out: "hogehoge"

よって構造違うのでキャストもできない

f := Fuga(h) // compile error

最近知った。以上。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1