假设有如下结构体定义
```
type Author struct {
name string
}
type Publisher struct {
name string
}
type Category struct {
name string
}
type BookBase struct {
name string
page int
}
type Book struct {
base BookBase
author Author
publisher Publisher
category Category
}
```
如果想要`New`一个`Book`类型的`struct`, 有如下两种方式
方式一:
```
func New(author Author, publisher Publisher, category Category, base BookBase) Book {
return Book{
base: base,
author: author,
publisher: publisher,
category: category,
}
}
```
方式二:
```
func New(authorName string, publisherName string, category string, id int, title string, content string) Book {
return Book{
base:BookBase{
articleId: id,
title:title,
content:content,
},
author:Author{name:authorName},
publisher:Publisher{name:publisherName},
category:Category{name:category},
}
}
```
如果使用**方式一**,客户端代码大概下面这样
```
func main() {
author := Author{name:"小明"}
publisher := Publisher{name:"宇宙出版社"}
category := Category{name:"神经病学"}
base := BookBase{
name:"论大脑的疑难杂症",
page:1000,
}
// new a book
book := New(author, publisher, category, base)
fmt.Println(book)
}
```
如果使用**方式二**,客户端代码大概下面这样
```
func main() {
// new a book
book := New("小明", "宇宙出版社", "神经病学", 1000, "论大脑的疑难杂症")
fmt.Println(book)
}
```
请问哪种`New`更符合Gopher习惯呢?或者是否有其他更好的方式。
完整代码请参考 [Go Playground](https://play.golang.org/p/0SyaZDnRP68)
有疑问加站长微信联系(非本文作者)