LoginSignup
1
1

More than 3 years have passed since last update.

GoのInterfaceを理解する

Posted at

はじめに

この記事は私と同じようにGoを勉強し始めたものの
interfaceを理解できない方へ向けたものとなっております。
interfaceは2個の意味が存在しています。

  • なんでも入れられる型 interface{}
  • 構造体などに紐づけ出来る書き方

今回は後者のほうを説明していきます。
ちなみに関数名などは適当なので申し訳ございません。

コード

package main

import (
    "fmt"
)

type Fish interface {
    Place()string       //住んでいる場所 
}

type Sanma struct {}
type Aji struct {}

func (s *Sanma)Place()string{
    return "Japan"
}

func (a *Aji)Place()string{
    return "Europe"
}

type Sea struct {}

func(s *Sea)seafish(fish Fish){
    fmt.Println("どこに住んでるの?:" + fish.Place())
}

func main(){
    sanma := &Sanma{}
    aji := &Aji{}
    sea := Sea{}
    fmt.Println(sanma.Place())
    fmt.Println(aji.Place())

    sea.seafish(sanma)
}

解説

上記のサンプルコードはinterfaceを使ったものとなっています。
Fishというinterfaceを宣言し、そこにPlaceという関数を宣言します。
SanmaとAjiという構造体を宣言します。作成した構造体のメソッドとして
Place関数を宣言します。interfaceにあるすべての関数を宣言するだけで紐づけすることができます。
この事によりSea構造体のseafishメソッドの引数にFishと紐づいている構造体を引数として渡すことができます。

interfaceの重要性

もしinterfaceを使わない場合はseafish関数の引数が各構造体を引数とし
Aji用のseafishとSanma用のseafishを宣言しなければいけなくなり、コードが長くなってしまいます。

終わりに

godoc見ていくといろいろとinterfaceで宣言されているので見てみると面白いかもしれません。
最後まで読んでいただきありがとうございました。

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