Open3

Goの覚え書き

typepoodletypepoodle

不変ならarrayにしておく

コーディング規約的な


var prefecture = [47]string{
    "北海道", "青森", "略...", "沖縄",
}

typepoodletypepoodle

Sliceにメソッドをはやして使う

キャストすると使いやすいと思った小並感
基本[]Typeで、メソッドを使いたいときはTypes([]Type).Method()

type Book struct {
	Id     int64
	Title  string
	ISBN   string
	Author string
	Price  uint
}

type Books []*Book

func (b Books) Unique() Books {
	m := make(map[int64]*Book)
	for i := range b {
		if _, dup := m[b[i].Id]; !dup {
			m[b[i].Id] = b[i]
		}
	}
	b2 := make([]*Book, len(m), len(m))
	i := 0
	for _, v := range m {
		b2[i] = v
		i++
	}

	return b2
}

func (b Books) Print() {
	for i := range b {
		fmt.Println(*b[i])
	}
}

func main() {
	var books = []*Book{
		{
			Id:     1,
			Title:  "title1",
			ISBN:   "ISBN-1234",
			Author: "yamada",
			Price:  3450,
		},
		{
			Id:     1,
			Title:  "title1",
			ISBN:   "ISBN-1234",
			Author: "yamada",
			Price:  3450,
		},
		{
			Id:     2,
			Title:  "title2",
			ISBN:   "ISBN-1232",
			Author: "yamada",
			Price:  1350,
		},
	}

	uniqueBooks := Books(books).Unique()
	uniqueBooks.Print()
        //{1 title1 ISBN-1234 yamada 3450}
        //{2 title2 ISBN-1232 yamada 1350}
}

typepoodletypepoodle

gormを見てたら出てきたのでメモ
メソッドの返り値に名前を付けるとreturnだけで返せる

import "time"

type User struct {
    Name     string
    Birthday time.Time
}

func NewUser(name string, birthday time.Time) *User {
    return &{
        Name:     name,
        Birthday: birthday,
    }
}

func (u *User) Hoge() (user *User) {
    //...do something
    return
}

func (u *User) Fuga() (user *User) {
    //...do something
    return
}

func main() {
    user := NewUser("taro", time.Now())
    user.Hoge().Fuga()
}