0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Go Interfaceの実装漏れを検知する

Posted at

はじめに

GoのInterfaceの実装です。Interfaceを利用すると実装、テストが楽になるのでInterfaceを実装したサンプルを記載します。

実装

ディレクトリ構成
~/go/src/go_sample$ tree
.
├── domain
│   ├── service.go
│   └── user.go
├── go.mod
└── main.go

2 directories, 4 files
main.go
package main

import (
	"fmt"
	"go_sample/domain"
)

func main() {
	user := domain.User{}
	fmt.Println(user.Walk())
}
service.go
package main

type IUserService interface {
	Talk() string
	Walk() string
}
user.go
package domain

type User struct {
	Name string
	Age  int
}

func (u User) Walk() string {
	return "歩きます"
}

// func (u User) Talk() string {
// 	return "話します"
// }

 →Talk()はあえてコメントアウトしてます。

実行結果
~/go/src/go_sample$ go run main.go
歩きます

課題

Interfaceを定義していないので、実装漏れが出てきてしまいます。そこで、Interfaceを利用して実装します。

user.go
package domain

var _ IUserService = User{}

type User struct {
	Name string
	Age  int
}

func (u User) Walk() string {
	return "歩きます"
}

// func (u User) Talk() string {
// 	return "話します"
// }

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?