April 27, 2015

GOLANGs weird conventions

I have been writing Go programs for a little bit now and have found them not too bad to write. It is a C-style language that makes picking it up easy if you come from nodejs or C#. But, there are some weird nuances that you have to get use to if you do decide to pick up some Golang.

Here goes the list:

  1. Types, variables and functions that are lowercase are private.
    This is a big frustration when you first start, as there is no hint towards it. It’s hard to say I don’t like this rule, as it enforces style. This can be a good thing and is like getting a code linter for free. It is an issue when you are first building golang projects, as you do not know why you can not see a member. It would be nice to have the compiler hint towards the lower/uppercase issue.
  2. Types and Interfaces define functions differently than Java and C#.

    I think golang is going back to the header and source file roots on this one. Basically, you define members and function signatures in your type signature. Then if you want to define the implimentation, you would make sure you add the type before the function name, like this example:

     package data import ( "io/ioutil" ) type IDataAccess interface { Save(key string, value string) Load(key string) string } type File\_access struct { FileLocation string } func (r File\_access) Save(key string, value string) { ioutil.WriteFile(r.FileLocation, []byte(value), 0777) } func (r File\_access) Load(key string) string { var value, \_ = ioutil.ReadFile(r.FileLocation) return string(value) } 

    This shows that the interface IDataAccess describes the method signatures, and File\_Access describes the fields of the struct. But in order to implement a File\_access struct, you need to add a (r File\_access) to tell golang that you are part of that struct. Weird.

  3. What does (r * File\_access) that (r File\_access) doesnt.
    In the previous example, we could tie the function to a pointer to the struct or not. This is confusing, can I only call the function if it is a pointer or not? I think this is not needed, but maybe I’m wrong. It seemed to have no affect, so whatever.
  4. Creating a struct vs other stuff.
    If you want to create a struct, you can use this way: data.File\_access{FileLocation: “test.txt”} , but if you want to just call some functions, you can use this way: new(model.File_access). The difference is that one is just a bunch of functions in a namespace (package) and the other is a struct. This is confusing and leaves me wishing there was one way to create these.

While many of these items are complaints, I do enjoy the language. I just wish some of these language paradigms were cleaned up thats all. If you can explain some of these to me, leave a comment!