LoginSignup
0
0

More than 3 years have passed since last update.

【Golang】interface型

Posted at

【Golang】interface型

Golangの基礎学習〜Webアプリケーション作成までの学習を終えたので、復習を兼ねてまとめていく。 基礎〜応用まで。

package main 
//インターフェース
//指定したメソッドを保持して欲しい時にインターフェースを使う
//異なるstructで共通のメソッドを持たせたい。

/*interface用途

1、異なる構造体で共通のメソッドをまとめられる。

2、どんな型も入るが、関数内で計算などを処理する場合は型アサーションする必要がある。

3、カスタムエラー、Stringerを設定できる。
*/



//interface1の使い方
import (
    "fmt"
)

//interface 型みたいな感じ
//同じメソッドを持つstructをまとめる
type Human interface {
    //共通のメソッドを持つ
    Say() string
}

type Man struct {
    Name string
}

type Woman struct {
    Name string
}

type Dog struct {
    Name string
}


//名前を書き換える場合 アドレスで渡す必要がある
func (m *Man) Say() string {
    m.Name = "Mr." + m.Name
    fmt.Println(m.Name)
    return m.Name
}

//名前を書き換える場合 アドレスで渡す必要がある
func (w *Woman) Say() string {
    w.Name = "Mrs." + w.Name
    fmt.Println(w.Name)
    return w.Name
}

//interfaceがHumanの関数
//Sayを持つ型なので、実行できる
func Speak(h Human){
    h.Say()
}


func main() {
    //structを作成 Human
    //指定したメソッドを保持して欲しい時にインターフェースを使う
    //say()メソッドを持つ
    //変数名 intarface = struct
    //var mike Human = Person{"Mike"}
    //mike.Say()でもできる。ので正直メリットがわからない筆者。
    var mike Human = &Man{"Mike"}
    var nancy Human = &Woman{"Nancy"}
    Speak(mike)
    Speak(nancy)

    //Dogはintarfaceを持たない
    //Say()を持たないとエラーになる
    var dog Dog = Dog{"dog"}
    //Speak(dog)
}
0
0
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
0