Best design to copy a struct

126 views
Skip to first unread message

Thomas S

unread,
Apr 20, 2020, 4:55:48 PM4/20/20
to golang-nuts
Hello,

In regexp package, the "copy" function is implemented like this :

func (re *Regexp) Copy() *Regexp {
   118  	re2 := *re
   119  	return &re2
   120  }

But most of the time for getting a copy of a struct, I do something like this :
func (re Regexp) Copy() *Regexp {
   119 	return &re
   120  }
What do you think ?
Do I nitpick?

Thank you dear gophers,
Thomas

Ian Lance Taylor

unread,
Apr 20, 2020, 6:42:39 PM4/20/20
to Thomas S, golang-nuts
For stylistic reasons, and to avoid confusion, it's often best for all
methods for a specific type to be either all pointer methods or all
value methods. There are exceptions, but they are rare. For the type
regexp.Regexp, all methods are pointer methods.

Other than that, I agree that your suggestion would work.

Ian

Thomas S

unread,
Apr 21, 2020, 5:09:38 AM4/21/20
to golang-nuts
I did not know this stylistic guideline.

Thank you Ian !

Le mardi 21 avril 2020 00:42:39 UTC+2, Ian Lance Taylor a écrit :

Kevin Chadwick

unread,
Apr 21, 2020, 7:34:18 AM4/21/20
to golang-nuts
On 2020-04-21 10:09, Thomas S wrote:
>> But most of the time for getting a copy of a struct, I do something like this :
>>
>> func (re Regexp) Copy() *Regexp {
>>    119 return &re
>>    120  }

If you are just trying to shallow copy a struct then I find this pointer usage
distasteful.

Far more readable would be

structname2 := structname

or (I wouldn't do this)

func copyStructName(data structname) structname {
return data
}

Caveat: I'm fairly new to go (< 2 years) and dislike a lot of idiomatic code.

e.g. Some Go books say, for clarity I have written this like this but you will
often see it written like this.

Personally I will use the clearer one, not the shorter one, every time??
Reply all
Reply to author
Forward
0 new messages