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?

コレクション型を定義する

Posted at

コレクションをレシーバにメソッドを定義することはできない

type User struct {
	ID   int
	Name string
	Age  int
}

// invalid receiver type []User
func (us []User) IDs() []int {
	var ids []int
	for _, u := range us {
		ids = append(ids, u.ID)
	}
	return ids
}

そんな時はコレクション型を定義する

package main

import "fmt"

type User struct {
	ID   int
	Name string
	Age  int
}

type Users []User

func (us Users) IDs() []int {
	var ids []int
	for _, u := range us {
		ids = append(ids, u.ID)
	}
	return ids
}

func main() {
	users := Users{
		User{
			ID:   1,
			Name: "Paul",
			Age:  82,
		},
		User{
			ID:   2,
			Name: "John",
			Age:  40,
		},
	}

	fmt.Println(users.IDs()) // [1 2]
}

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?