Lets say you are working with a func that returns a bool as to whether a user has been active in the last month.
In Ruby:
def active_in_last_month?;end
In C#
public bool WasActiveInLastMonth(){}
What is the idiomatic way of naming boolean predicate functions in Go?
The usual convention to name methods that return boolean is to prefix verbs such as 'is' or 'has' to the predicate as a question, or use the predicate as an assertion. For example, to check if a user is active, you would say user. isActive() or to check if the user exists, you would say user. exists().
There is no standard naming convention specific to boolean-returning methods. However, PEP8 does have a guide for naming functions. Function names should be lowercase, with words separated by underscores as necessary to improve readability.
tl;dr
func wasActiveInLastMonth() bool
Full Answer
I looked in the GitHub repos of some well known open source projects, picked a semi-random file, and found the following:
Etcd lease/lessor.go
func (le *lessor) isPrimary() bool
Kubernetes service/service_controller.go
func (s *ServiceController) needsUpdate(oldService *v1.Service, newService *v1.Service) bool
func portsEqualForLB(x, y *v1.Service) bool
func portSlicesEqualForLB(x, y []*v1.ServicePort) bool
Consul agent/acl.go
func (m *aclManager) isDisabled() bool
Docker Moby (open source upstream of Docker) cli/cobra.go
func hasSubCommands(cmd *cobra.Command) bool
func hasManagementSubCommands(cmd *cobra.Command) bool
I would say that these four projects represent some of the most well reviewed and famous go code in existence. It seems that the is/has pattern is very prevalent although not the only pattern. If you choose this pattern you will certainly be able to defend your choice as a de facto idiom.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With