In Go is naming the receiver variable 'self' misleading or good practice?

前端 未结 6 1444
青春惊慌失措
青春惊慌失措 2020-12-01 02:42

I have seen a fair amount of blogs & videos on Go and as far as I recall, none of the authors use \'self\' or \'this\' for the receiver variable when writing methods. H

6条回答
  •  眼角桃花
    2020-12-01 03:38

    I concur with Oliver Goodman's answer and admire the courage of his convictions in the face of such overwhelming odds.

    Basically, the naysayers are saying that using "this" (my preference) as the receiver variable does NOT have precisely the same meaning as in other languages. So we should avoid it to preempt potential gotchas and keep confusion to a minimum.

    But, of course, the same could be said about -> and ., not to mention many other C-like facets of Go (over which we have no control).

    However, using "this" in the way the OP implies makes it so much easier to understand context. And since we know we are programming in Go, we understand that it has different implications compared to other languages.

    Using "this" also implies that our type ("class") methods are "conventional". If some weirdness is expected then you can always use another receiver moniker to emphasise this fact.

    But let's not throw the baby out with the bathwater!

    From the very start, I have found that hard core Gophers tend to be very rigid and unbending. But I must admit that this has served the language well in many many areas. And I take my hat off to them in that respect.

    However, this same unyielding mindset has unleashed problems in other areas, The GOPATH craziness is the most obvious example.

    Listening to the experts is no excuse for not thinking things through. Even the experts have blind spots and hang-ups whose magnitude is often in direct proportion to their speciality.

    Short answer: Use the convention that suits you best!

提交回复
热议问题