151 points · by iand · 14y ago · 97 comments
import "image/color"
x := color.RGBA{255, 255, 255, 0}
Perhaps I'm naive, but I thought you could do this in basically any language, including Java (it's been a while).EDIT: Not sure why this was downvoted, but it's a trivial Google search[1] to show that this is indeed something that you can do in Java:
import javax.swing.JOptionPane;
class ImportTest {
public static void main(String[] args) {
JOptionPane.showMessageDialog(null, "Hi");
System.exit(0);
}
}
Which, without the import, would force you to use the full name as the author alludes: class ImportTest {
public static void main(String[] args) {
javax.swing.JOptionPane.showMessageDialog(null, "Hi");
System.exit(0);
}
}
I'm not intending to bash Go (it has the largest quantity of awesome features of any language I've seen in a long time), nor necessarily to defend Java. It just seems a bit disingenuous to claim that this is exceptional behavior.[1] http://www.leepoint.net/notes-java/language/10basics/import....
x := color.RGBA{255, 255, 255, 0} is instantiating an RGBA type from the image/color package
import org.somelib.colors.*
x = new RGBA(255, 255, 255, 0);
where RGBA is some class defined in the org.somelib.colors package. import org.somelib.*
x = new colors.RGBA(255, 255, 255, 0);
So you don't have to bring all the classes into scope, but you don't have to write out the full path to use them either. Just the last bit of the package-name as a qualifier.One trait that I find frustrating is how pedantic Go is about types.
For example, if I have a float x and an int y, I can't write x / y, I have to write x / float64(y)†. The intent is to force awareness of type conversions that introduce subtle gotchas, but I don't see how it applies to the case float / int.
A better example of the same phenomenon is that alias-style types need to be explicitly cast to their aliased types, which introduces pointless noise into what would otherwise be a nice way of 'marking up' the semantic role of variables and arguments (think type index uint).
†Notice there is a common-or-garden 'int' but no common-or-garden 'float', apparently because one should always be aware of precision. Unfortunately, because of the alias type issue I mention above, 'type float float64' doesn't help.
Does the int get converted to a float for this calculation? is sizeof(int) == sizeof(float)? Then you can lose accuracy in the conversion; MAX_INT is larger than the largest same-sized float that can be represented without rounding error.
Type 1 | Type 2 | Allowed?
--------------------------
float32 | int32 | n
float32 | int64 | n
float64 | int32 | y
float64 | int64 | n
etc...
Seems a bit odd to have the majority of conversions banned, but allow some random-seeming exceptions that are safe.Since implicit conversions are almost always either lossy or dangerous (think 'Fahrenheit(32) - Celsius(64)'), I think it makes sense to remove implicit promotions entirely.
Keep at it long enough, and you will.
Moreover, if float means float64 (as I'd suggest be the case) and int continues to mean int32 (which it won't forever), then a lot of common cases would not require explicit casting and be safe.
Yes, but too much variance in how the compiler reacts depending on local implementation details can be quite messy. The principle of least surprise would recommend leaving the feature out, especially since Go dispenses with compiler warnings. Otherwise. we could have the situation where something compiles just fine on your desktop, then breaks when compiled for a different platform like NaCL. How would the developer know this on the desktop, ahead of time? By leaving the feature out, you get a more informant and reliable tool.
And to be honest, I like code that is explicit in what it does. That makes things easier to read and comprehend.
Although your example argues against round-tripping the conversation rather than the conversion per se. Which I'm not proposing.
In your example, my proposal would have an index get automatically cast to an int, then undergo division, remaining an int. Who knows why you divided it? But you wouldn't get an index back.
This is a common misconception of those who work mainly in compiled languages. In some dynamic languages, you don't just have the same edit-test-debug cycle. Advanced users of dynamic languages can conduct mini edit-test-debug within all the parts of the larger scale edit-test-debug cycle.
Go is not object-oriented. This, in my opinion, is a massive plus for the language....In the real world, things are fuzzy and they spread across multiple conceptual boxes all at once. Is it a circle or an ellipse? Is she an employee or a homeworker? Classifying things into strict type hierarchies, although seductive, is never going to work.
Here, the author is simply wrong. This is another common misconception about OO. You don't need strict type hierarchies. You don't even need classes at all for OO.
EDIT: Other than that, an overall good review.
There are almost an infinite number of definitions of OO, I suspect the author was referring to the generally accepted and most widespread ones, which include classes and inheritance as some of their most fundamental characteristics.
Or as Paul Graham put it ( http://harmful.cat-v.org/software/OO_programming/ ):
"The phrase "object-oriented" means a lot of things. Half are obvious, and the other half are mistakes."
Go implements (and improves on) the obvious ones (which by the way mostly have been around for longer than the term OO itself), while avoiding the rest.
Yes, but everyone I know who does real work with Objects knows that the textbook definitions aren't what people do with real systems. That makes it sound like the author only knows the textbook definitions.
> Yes, but everyone I know who does real work with Objects knows that the
> textbook definitions aren't what people do with real systems. That
> makes it sound like the author only knows the textbook definitions.
Phrases like 'who does real work' and 'people do with real systems' makes it sound a bit like a 'no-true-scotsman'. I imagine that was not your intent.Anyway, I think the point is that the common perception of object systems are likely those commonly used in Java, C++, and C#. I say 'likely' simply because I am guessing that those are the more popular by volume of code written. Go has a different approach than those.
Specifically, you say this:
I can hear the die-hards screaming already about encapsulation, inheritance and polymorphism. It turns out that these things are not as important as we once thought.
And then you proceed to give examples that only attempt to refute the usefulness of type hierarchies, without addressing encapsulation and polymorphism. I'd be curious to know what facilities, if any, Go provides for these concepts.
Any die-hards screaming about all 3 of those should be viewed with a bit of skepticism. When I talked about this a lot, folks were "meh" about inheritance, especially class-based inheritance. The only thing I see as being worthy of die-hard adherence is polymorphism. Encapsulation is there to help enable polymorphism. I'll note that the degree of encapsulation varies amongst systems that call themselves OO.
To me your "simplification" is a bit of a straw man.
[1]: http://www.cs.utexas.edu/~wcook/papers/OOPvsADT/CookOOPvsADT...
This title could easily have refferred to the correct meaning of 5 weeks with the programming language Go, 5 weeks playing and studying the game Go, or in a slightly colloquial usage, 5 weeks of constantly doing things and going.
And those are just the meanings that make sense in this context. It is also a verb with a wide variety of (related) meanings and forms a command part of a command in multiple computer languages (T-SQL uses Go, goto is infamous in Basic, etc).
http://en.wikipedia.org/wiki/Go!_%28programming_language%29
It's not the only one. Try Googling for "Processing" and getting relevant programming language results.
When I searched for "why is golang called go" Google actually suggests I change "golang" to "google" which is kind of funny.
I do like exceptions in Python where their use is ubiquitous and there is garbage collection. I detest checked exceptions in Java because you are forced to handle things at a level you often don't want to.
I'm 65% certain Go made a mistake not using exceptions, but would love to hear from others.
foo, err := GetDataFromDatabase()
if err != nil {
foo, err = GetDataFromLocalFilesystem()
}
if err != nil {
foo, err = GetDataFromNetworkFilesystem()
}
return foo, err
There is an exception-like mechanism called 'panic', but it shouldn't be used as a control flow tool. Panic is reserved for unrecoverable errors, not mundane situations like a failed query.The article author is quite wrong when he says "exceptions are broken by design because they force errors to be handled at points far away from the cause". Exceptions don't force you to handle errors at any particular location; they allow you to handle errors anywhere in the stack. On the other hand, return values do force you to handle errors then-and-there, which 90% of the time is a half-dozen stack frames away from your handler.
1. Handling a failed assumption, which will cause the code that follows to be incorrect (I need the contents of this file to do my task, but it doesn't exist, so I can't do my task)
2. Handling a failed operation, which there is a straightforward way of working around (if I can't write to my log file, maybe write to stderr instead instead and give up)
The trouble is that the 'inner' code doesn't know which of these a given failure is, because it is context specific. Seems like with languages like Java, the default is 1, whereas with Go it is 2. They're kind of equivalent, though, because you can always convert a !ok into a panic(...).
But certainly exceptions are the nuclear option, so it seems reasonable to me that they shouldn't be the default for common operations that can fail.
if foo, err := GetDataFromDatabase(); err != nil {
if foo, err = GetDataFromLocalFileSystem(); err != nil {
foo, err = GetDataFromNetworkFilesystem()
}
}
return foo, errI've not seen a standard error object either which means every place that looks at an error has to be intimately aware of what it is looking at. There is an os.Error but that appears to be string only so there is no errno equivalent value inside.
In languages with exceptions there is a base error/exception/throwable that has reason fields as well as methods to get tracebacks which are extremely useful.
I'm now 85% convinced Go made a mistake not using exceptions.
I think Go's main approach is this: errors are not exceptional. Errors happen all the time, and should be considered part of the normal control flow of the program, not something to be shoved into a hidden compartment and dealt with later.
Thus using the usual control flow statements to check for errors is entirely appropriate, and it's immediately obvious when reviewing the code if someone has failed to do the right error checking.
BTW there is no os.Error type any more. There's a language-defined "error" type, which is an interface containing a single method:
type error { Error() string }
You only need to be intimately aware of what you're looking at if you want to take some different action based on the kind of error. This is actually quite rare (usually you care only that something failed, not how it failed), but when you need to, generally the calling package defines an error type that represents a particular kind or class of errors (for example http://golang.org/pkg/os/#LinkError)
Depending on git master is cowboy coding at its most cavalier; build systems should prize repeatability above all else.
1. Hope that the projects you depend on have a tag that you can reference as your import or that you can acquire specifically with `go get`
2. Fork them and keep track of them yourself.
3. Use the tool (I can't find the link) that manages version dependencies per-project so that you can have different versions for different projects based on your needs (think virutalenv).
> Enforcing a brace placement style and other conventions means the compiler can be super fast.
Surely the lexical-analysis phase is not the bottleneck in compilation? (The context strongly suggests that 'other conventions' means 'other lexical conventions'.)
Can I import Java libraries into Go? If I can't find a Go library to do what I need, what are my options besides messaging to another process, or (presumably) finding a equivalent C library (I don't trust my C skills enough to make wrapping something a confidence inspiring no-brainer).
Is there general language/library interop details out there any golangers could point me towards?
No. Go compiles to machine code, not the JVM.
Go's built in cgo tool makes it very easy to wrap C code. See http://golang.org/doc/articles/c_go_cgo.html. Crucially, you can write most of the wrapper in pure Go and the C boilerplate code is generated automatically.
To have a pure binary would effectively require a reimplementation of the framework of Dalvik and all the various classes/methods and would be a huge undertaking. It would be extremely unlikely to install on existing Android versions and would only be in a future version. Or in other words it would be many many years before you could depend on it being on Android devices even if this was done for the next Android version.
The shared library thing is the biggest problem though. Android applications are really mashups of components from the same app or others (see Activities, Services, Content Providers, Receivers). There isn't actually a main() method or equivalent. Instead the components are loaded and called as needed.
var x int
var foo map[string]int
var dummy []int
compared to var int x
var map[string] int foo
var []int dummyConsider: int* i, j (or rather int *i, j)
int* x, y;
when you meant to declare both x and y as int pointers, here only x will be a pointer and y will be a straight int.Obviously the go designers could have chosen to simply make this mean that both x and y are pointers, however this would be somewhat confusing for those familiar with C.
As iand says, there is a rather good article on this which goes into a lot more detail - http://golang.org/doc/articles/gos_declaration_syntax.html
But goodness I love writing Go. Sorry, it's hard for me to be terribly specific outside of, for some reason, I'm very productive with it and I love the standard libraries. And where they're lacking Google Code, Github and IRC/play.golang.org make up for it.
Unfortunately, the standard libraries that I've sampled have felt inconsistent. Two examples I happen to remember:
1. The strconv package has a Atoi (a wrapper around ParseInt) but no Atof -- instead you use ParseFloat directly, and you have to give it as a second argument one of the integer values '32' or '64' to set the precision it parses at (why not use an enum or two funcs?).
2. The bytes package has versions of Index that search for single bytes (IndexByte) as well as byte slices (Index), a nice performance-friendly touch. However Split only has the byte slice version. SplitByte would probably be twice the speed.
If you are going to write a package to stand the test of time, be consistent.
(edit: I got Atoi the wrong way round)
I think they made the right choice there; the Go team seems very good about optimizing only where it matters; there's lots of low hanging fruit, but the majority of it isn't very useful fruit.
I did 128 runs on a byte array of length 2^24. It has delimiters placed at positions {2^i, i < 24}.
I tested my implementation against both the "bytes" package implementation, and a copy of the relevant portions of the "bytes" package (to account for any odd effects of inlining and separate compilation). I did the set of timings twice in case there was any GC.
Here's the wall time in milliseconds for the three implementations, on a 2010 Macbook Air.
mine 3313 copy 4709 bytes 5689 mine 3327 copy 4660 bytes 5660
My single-byte implementation is about 40% faster than the local version, and 70% faster than the "bytes" version. Not quite twice, but I wasn't far off.
But aside from performance, there is just consistency of interface. Once you've established a 'Byte' variant of some functions, you should do it for all the common functions.