Namespacing hack using method on empty type

201 views
Skip to first unread message

dani.m...@gmail.com

unread,
Aug 3, 2016, 9:19:52 AM8/3/16
to golang-nuts
Hi all, just saw a piece of software that make large use of methods defined on (basically) empty structs as a namespacing hack.

Example:

type Foo struct {
}

func
NewFoo() Foo {
 
return Foo{}
}

var (
  foo
= NewFoo()
)

func
(self Foo) Bar1 () {
}


func
(self Foo) Bar2 () {
}


This way I can call bar1 and bar2 as if they were func exposed on the "package" foo, like this:

foo.Bar1()
foo
.Bar2()

I assumed that is bad practice. What do you think?

Thanks

atd...@gmail.com

unread,
Aug 3, 2016, 11:07:35 AM8/3/16
to golang-nuts
No it can have its uses.

It really depends on what you are doing. However, I've never done this as a way to declare some kind of namespace.

Typically, I use that in testing when I want a dummy type to implement an interface.

That's just an example.

It can be used also if you export the struct type. That allows to transfer a group of functions (closer to your idea of namespace).
Instead of exporting each function separately.

dc0d

unread,
Aug 4, 2016, 6:49:03 AM8/4/16
to golang-nuts
Personally I do that (despite that everyone advocates against it). Just remember your struct should be just "struct{}" and nothing else. This helped me to use shorter & cleaner names for my functions - actually it converts a function pile to a batch of functions).

Christoph Berger

unread,
Aug 5, 2016, 12:19:31 AM8/5/16
to golang-nuts
Are there any advantages over using real packages?

Christian Joergensen

unread,
Aug 5, 2016, 5:10:30 AM8/5/16
to golang-nuts
Hi,

For starters, packages can't implement interfaces.

Cheers,

parais...@gmail.com

unread,
Aug 5, 2016, 5:28:32 AM8/5/16
to golang-nuts
You just declared a global variable. the standard library does exactly that with http Client. I assume if it is in the std lib I don't see why you shouldn't do that yourself.

Christoph Berger

unread,
Aug 5, 2016, 2:23:29 PM8/5/16
to Christian Joergensen, golang-nuts
Hi Christian,

You’re right on this, but my question is about another aspect. The thread starter’s question was about using structs for namespaces (instead of packages). My question is, why would someone want to use empty structs for creating a name space if a package already does this. After all, packages are the natural means for creating a namespace.

Thx


--
You received this message because you are subscribed to a topic in the Google Groups "golang-nuts" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/golang-nuts/yCgjgpQsbHc/unsubscribe.
To unsubscribe from this group and all its topics, send an email to golang-nuts...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply all
Reply to author
Forward
0 new messages