LoginSignup
0
1

More than 5 years have passed since last update.

interfaceをsliceで渡す抽象化方法

Last updated at Posted at 2017-07-05

構造体を抽象化して処理させたい場合で、かつsliceで処理させる場合。

package main

import "fmt"

type PersonInterface interface {
    Greet() string
}

type SalesPerson struct {
    Name string
}

type Operator struct {
    Name string
}

func (s *SalesPerson) Greet() string{
    return "こんにちは、私は" + s.Name + "です"
}

func (o *Operator) Greet() string{
    return "こんにちは、私は" + o.Name + "です"
}

func main(){
    people := []PersonInterface{}

    people = append(people, &SalesPerson{Name: "山田"})
    people = append(people, &Operator{Name: "鈴木"})
    Update(people)
}

func Update(people []PersonInterface){
    for _, v := range people {
        fmt.Println(v.Greet())
    }
}

結果:

こんにちは、私は山田です
こんにちは、私は鈴木です
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