log

日記です

golangのinterface

package main

import "fmt"

func main() {
	var repo UserRepository
	repo = NewUserRepositoryDB()
	user := repo.Resolve(1)
	fmt.Println("user:", user)
	user.Name = "ChangedName"
	repo.Save(user)
}

type User struct {
	ID int64
	Name string
}

type UserRepository interface {
	Save(user User)
	Resolve(id int64) User
}

type UserRepositoryDB struct{}
func NewUserRepositoryDB() UserRepositoryDB{
	return UserRepositoryDB{}
}

func (this UserRepositoryDB) Save(user User) {
	fmt.Println("[call] save:", user)
}

func (this UserRepositoryDB) Resolve(id int64) User {
	fmt.Println("[call] resolve:", id)
	return User{id, "user"}
}

実行

$ go run hoge.go
[call] resolve: 1
user: {1 user}
[call] save: {1 ChangedName}

HogeRepositoryでInterface切って、実装クラスはDIできるようにすると捗りそう。