1
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 3 years have passed since last update.

構造体のインスタンス作成時に&を付ける必要がある時

Posted at

Goでhttp.Clientを使う際に

transport := &http.Transport{}

なんで&付けないとダメなのだろうと調べてみた。
付けないと

client := http.Client{
    Transport: transport, // ここでエラーが出る
}

cannot use transport (type http.Transport) as type http.RoundTripper in field > value:
http.Transport does not implement http.RoundTripper (RoundTrip method
has pointer receiver)

怒られる。

RoundTrip method has pointer receiver

interfaceを実装する構造体で、メソッドにポインタレシーバを使うと
構造体を作成する際に、ポインタを取らないとダメらしい。

type Hoge interface {
	SetName(name string)
	GetName() string
}

type Sample struct {
	Name string
}

func (s *Sample) GetName() string {
	return s.Name
}

func (s *Sample) SetName(name string){
	s.Name = name
}

func main() {
	// var s Hoge = Sample{} これだと動かない
	var s Hoge = &Sample{} // これは大丈夫
	s.SetName("三井直樹")
	fmt.Println(s.GetName())
}

気を付けよう。

1
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
1
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?