LoginSignup
3
1

More than 5 years have passed since last update.

Go言語の独特な文法集

Posted at

Go言語の文法のうち、直感で分からなかったものをまとめておく。そのうち、増えていくかも。

embedded struct

定義

type <struct name> struct {
    <embedded struct name>
    <field>
    <field>
    ...
}

使い方

type Person struct {
    age int
    name string
}
type Student struct {
    Person
    name string
    grade int
    class string
}

student := Student{Person{10, "alice"}, "bob", 4, "C"}

student.Person.age // => 10
student.age // => 10

student.Person.name // => alice
student.name // => bob

説明

Student structの中に、Person structが組み込まれて(embedded)いる。Compositパターンの一種らしい。

type assertion

定義

<casted instance> := <instance>.(<type name>)
<casted instance>, <is_success> := <instance>.(<type name>)

使い方

type Dog interface {
    bark()
}
type PetDog struct {
    owner string
    bark()
}
func (PetDog dog) bark() {
    fmt.Printf("woof")
}
type GuidDog struct {
    trainer string
    bark()
}
func (GuidDog dog) bark() {
    fmt.Printf("Bow")
}

var d_pochi, d_hana Dog = PetDog{"alice"}, GuidDog{"bob"}

pd_pochi := d_pochi.(PetDog)
pd_pochi.bark()

// pd_hana := d_hana.(PetDog) // => panic
// pd_hana.bark()

if _, ok := d_hana.(PetDog); !ok {
    gd_hana := d_hana.(GuidDog)
    gd_hana.bark()
}

インスタンスの抽象型(インターフェース型)を具体型(インスタンス型)に変える。戻り値が一つの場合は、変換後のインスタンスが返される。また、型変換に失敗した時はpanicになる。戻り値が二つの場合は、一つ目に変換後のインスタンスが、二つ目に変換の成否が返される。変換に失敗した時は、一つ目にはnilが、二つ目にはfalseが返される。

3
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
3
1