Created
March 6, 2020 17:49
-
-
Save takashima0411/6e3eda0f5d46d1ca0718b1f93870fa35 to your computer and use it in GitHub Desktop.
polymorphism in Go.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import "fmt" | |
type IF interface { | |
GetID() int64 | |
GetName() string | |
} | |
type A struct { | |
id int64 | |
name string | |
} | |
func NewA(id int64, name string) A { | |
return A{ id, name} | |
} | |
func (a A) GetID() int64 { | |
return a.id | |
} | |
func (a A) GetName() string { | |
return a.name | |
} | |
type B struct { | |
id int64 | |
name string | |
} | |
func NewB(id int64, name string) B { | |
return B{ id, name} | |
} | |
func (b B) GetID() int64 { | |
return b.id | |
} | |
func (b B) GetName() string { | |
return b.name | |
} | |
func main() { | |
arr := make([]IF, 0, 10) | |
a := NewA(0, "hoge") | |
b := NewB(1, "fuga") | |
arr = append(arr, a) | |
arr = append(arr, b) | |
for _, val := range arr { | |
fmt.Printf("id : %d name : %s\n", val.GetID(), val.GetName()) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment