英文:
Prettier methods in Go Lang
问题
我正在寻找编写Go代码的最佳实践。我有两个非常相似的方法,我只想更好地编写代码,是否有一种将AddAuthor和AddTitle方法合并为一个方法的方式。
我在思考类似于func (t *Test) SetProperty("name", "alfa")的方法,但不知道如何改进这段代码。欢迎提供任何评论。如果您能给我一个关于风格和实践方面编写良好的Go代码的链接,我将不胜感激。
谢谢!
type Test struct {
Title string
Author string
}
func (t *Test) AddAuthor(name string) (*Test, error) {
if err := validateStringLength(name); err != nil {
return nil, err
}
t.Author = name
return t, nil
}
func (t *Test) AddTitle(title string) (*Test, error) {
if err := validateStringLength(title); err != nil {
return nil, err
}
t.Title = title
return t, nil
}
func validateStringLength(field string) error {
if len(field) > 255 {
return fmt.Errorf("field %v is too long.", field)
}
return nil
}
我将为您提供翻译后的代码部分。
英文:
I am looking for best practices while writing Go code. I have two methods they are very close in logic. I just want to code it better and is there a way of combining AddAuthor and AddTitle methods in one with Go.
I am thinking something like func (t *Test) SetProperty("name", "alfa") .. kind of an approach but don't know how to make this code better. Any comments are welcome. Also if you give me a link with well written Go Code in terms of style and practices, I would be glad.
Thanks,
type Test struct {
Title string
Author string
}
func (t *Test) AddAuthor(name string) (*Test, error) {
if err := validateStringLength(name); err != nil {
return nil, err
}
t.Author = name
return t, nil
}
func (t *Test) AddTitle(title string) (*Test, error) {
if err := validateStringLength(title); err != nil {
return nil, err
}
t.Title = title
return t, nil
}
func validateStringLength(field string) error {
if len(field) > 255 {
return fmt.Errorf("field %v is too long.", field)
}
return nil
}
答案1
得分: 4
这是一种实现方法:
func (t *Test) AddAuthor(author string) (*Test, error) {
return t.setString(&t.Author, author)
}
func (t *Test) AddTitle(title string) (*Test, error) {
return t.setString(&t.Title, title)
}
func (t *Test) setString(p *string, v string) (*Test, error) {
if len(v) > 255 {
return nil, fmt.Errorf("字段 %v 过长。", v)
}
*p = v
return t, nil
}
英文:
Here's one way to do it:
func (t *Test) AddAuthor(author string) (*Test, error) {
return t.setString(&t.Author, author)
}
func (t *Test) AddTitle(title string) (*Test, error) {
return t.setString(&t.Title, title)
}
func (t *Test) setString(p *string, v string) (*Test, error) {
if len(v) > 255 {
return nil, fmt.Errorf("field %v is too long.", v)
}
*p = v
return t, nil
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论