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 で private なメソッドは他パッケージでは実装できない

Last updated at Posted at 2022-07-21

これは何?

go で

go
type Foo interface {
	private()
}

みたいなインターフェイスがあって、この private を他パッケージで実装可能かどうか調べた。

C++ の場合

C++ の場合。
アクセス制御とオーバーライド可否は直行している。

c+++
struct base
{
private:
  virtual void foo() = 0;
};

struct derived : public base
{
private:
  virtual void foo() override {}
};

private なメンバ関数をオーバーライドできる。

たまにそういうコードを見る。まれに便利。

Go の場合

public なインターフェイスに private なメソッドを用意して。

foo/foo.go
package foo

type Foo interface {
	private()
}

それを別のパッケージで実装すると。

bar/bar.go
package bar

import 	foo "略/foo"

type bar struct {}

func (b *bar) private() {}

func NewBar() foo.Foo {
	return &bar{} //   *bar does not implement foo.Foo (missing private method)
}

エラー。
この「private」を「NotPrivate」に変えるとエラーが出なくなる。

そういうものらしい。

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?