Basically it doesn't have generics which means you have to do a lot of fuckery with interfaces to get to a level of abstraction that you get with generics. And it's still not really possible. You end up with a lot of duplicated code for compatibility with different types.
Best example is https://golang.org/pkg/sync/atomic/ the atomic package used for asynchronous arithmetic.
You have AddInt32, AddInt64, AddUint32....
I don't like Go either. That said, I have some feedback for the author. Meta: please timestamp blog posts, at least the month and year–in this case February 2018.
Anyway...
> Rob's resistance to the idea has successfully kept Go's official site and docs highlighting-free as of this writing.
This is mostly true but the Go Tour does have optional syntax highlighting.
> Java can now emit this warning for switches over enum types. Other languages - including ... Elixir ... similarly warn where possible.
Elixir doesn't actually. It's a dynamically-typed language and it doesn't do exhaustivity checking.
> higher-order functions that generalize across more than a single concrete type,
I believe the author is referring to parametrically polymorphic functions. Higher-order functions are ones that accept and/or return functions, and Go has first-class functions so it follows it has HOFs as well, e.g. https://golang.org/doc/codewalk/functions/
> the Go team's response of "vendor everything" amounts to refusing to help developers communicate with one another about their code. ... I can respect the position the Go team has taken, which is that it's not their problem,
Actually, I don't think that's it. Go's primary 'client' is Google, and Google source code famously vendors everything. Go is designed from the ground up to enable that strategy. Its suitability to others is a secondary consideration.
> The use of a single monolithic path for all sources makes version conflicts between dependencies nearly unavoidable. ... Again, the Go team's "not our problem" response is disappointing and frustrating.
But again funnily, it's perfectly suited for Google's monorepo.
> Go has no tuples
True, but it does have multiple return values, which is a use case for tuples. This specialization can be considered good or bad (imho, bad).
Also if things like try(bar(try(foo(try(baz()))))
are proposed by the Go team member(s), the "Control flow" section of the FAQ should be adjusted or deleted. It says
> Why does Go not have the ?: operator? > > There is no ternary testing operation in Go. You may use the following to achieve the same result: > if expr { n = trueVal } else { n = falseVal }
> The reason ?: is absent from Go is that the language's designers had seen the operation used too often to create > impenetrably complex expressions. The if-else form, although longer, is unquestionably clearer. A language needs > only one conditional control flow construct.
(emphasizes mine)
For reference:
Golang's reference time for formatting is "Mon Jan 2 15:04:05 MST 2006" or "01/02 03:04:05PM '06 -0700"
Internally time is: > The zero value of type Time is January 1, year 1, 00:00:00.000000000 UTC.
Go doesn't have type casts the way C does; instead, we have type conversions and type assertions, and you need to choose the one that's right for the situation. (Both would be a cast in C)
Conversions ask the compiler to change the representation of one value into another. For example, truncating a float32 into an int. This is required whenever the underlying types are different, or if the types have different names but the same underlying type. This is generally pretty performant, with the exception of converting between byte slice and string, which incurs an allocation and copy, which can be quite costly.
What you are using here, though, is a type assertion, which is required when you have an interface but need to pull out the concrete type from it (or check if it matches a different / broader interface). For a concrete type check, this is pretty fast, because an interface is basically a type pointer and a value pointer, so you can think of it like a conditional... If the type pointer matches, extract the value.
So, could this be slow? Yes, but generally your latency to your user and/or the database will be much larger, so unless you are doing it millions or billions of times, there are probably other things which can be optimized first if you find it is getting slow.
> > higher-order functions that generalize across more than a single concrete type, > > I believe the author is referring to parametrically polymorphic functions. Higher-order functions are ones that accept and/or return functions, and Go has first-class functions so it follows it has HOFs as well, e.g. https://golang.org/doc/codewalk/functions/
I think the author was referring to HOFs, but the "generalize across more than a single type" part was meant as an additional qualifier, not as a description of what "higher-order function" means. That is, yes, Go may have some HOFs, but it doesn't have HOFs that work with multiple types. Specifically it doesn't have map
, filter
or fold
, which I believe many would consider the quintessential HOFs.
If you don't care about branding, that's totally fine: ignore this and go back to writing awesome Go programs. If you're already using Go, you're probably not the target audience for this, and that's 100% OK.
Beware knee-jerk negative reactions. It's always easy to be a quick critic. It takes more time to absorb something new and different and give it a fair evaluation. The fact (like it or not) is that branding and a professional look will help with not turning away other Go developers, not to mention the people they have to convince to let them use Go at work. Replacing the 1995-esque web design we've been using (which was mostly my doing) is a positive thing for more Go adoption, which grows the Go community and helps everyone.
Also, in case everyone forgot, this was the old Go logo: https://golang.org/doc/go-logo-white.png. The new one captures the same spirit but ends up being a bit more versatile.
SSA for all architectures, not just amd64. This is a huge win for ARM, since ARM isn't good at executing bad code like x86 is.
More SSA optimizations, and better generated code in general.
New, faster compiler frontend parser.
The compiler frontend can start assuming an SSA backend, and do less work for the backend, which will actually make the backend faster too. One recent example: https://go-review.googlesource.com/27461 and
Smaller binaries. e.g. https://golang.org/cl/26668
Crawshaw is working on the "plugin" execution mode.
Bunch of TLS updates.
Who knows. It's still early days. But SSA everywhere is the main theme.
Although the project leaders happen to be Google employees that are paid to work on Go, it is not a Google product and the title makes it sound like the decisions of the Go team are driven by Google executives.
The only control Google has over Go is that they own employee copyrights, so they have partial ownership of the code: https://golang.org/AUTHORS
Neat exploration. I don't think I understand why your Rust program is still slower. When I ran your programs on my system, the Rust program was faster.
If you're looking to write the fastest line counter, then I'm pretty sure there is still (potentially significant) gains to be made there. My current idea is that a line counter based on libripgrep is possible and could be quite fast, if done right. High level docs are still lacking though! I'm thinking a line counter might be a good case study for libripgrep. :-)
> Anyway what I have discovered so far is that Go seems to take reasonable defaults. Rust gives you more power, but also allows you to shoot yourself in the foot easily. If you ask to iterate the bytes of a file thats what it will do. Such an operation is not supported in the Go base libraries.
I don't disagree with this, but I don't agree with it either. Go certainly has byte oriented APIs. Rust also has <code>fs::read</code>, which is similar to Go's high level ioutil.ReadFile
routine. Both languages give you high level convenience routines among various other APIs, some of which may be slower. Whether you're programming in Rust or Go, you'll need to choose the right API for the job. If you're specifically writing programs that are intended to be fast, then you'll always need to think about the cost model of the operations you're invoking.
Here's how you use a priority queue in Go:
1.) Go to https://golang.org/pkg/container/heap/#example__priorityQueue and copy paste the code so you can use the standard library.
2.) Start using the heap interface and pointers to your queue to get things started.
3.) Get frustrated with interface{}
and the heap api so try and implement a "type safe" wrapper specialized to your queue.
4.) Realize you need to do it again for your next item type.
5.) Start refreshing your resume
It isn't a functional vs imperative debate. It is a complexity vs. simplicity debate. You've structured your argument as:
Go takes a different route. Adding more to a language makes it easier to do some things, but it also makes the language more complicated. There is a tragedy of the commons problem that shows up at the end of that road, where you have every language feature that anyone can stuff in. The devs have drawn a line, an opinionated, arbitrary line, and said they don't want to add every feature, and they have decided on a case by case basis.
I have to respect them for it, and I suspect that over time more people will appreciate it. Saying that they have a duty to programmers everywhere to add generics is narcissism masquerading as altruism. They don't have to do things your way.
I use go because I am completely fed up with languages with feature-itis. I don't want generics, and macros, and annotations, and derived types, and tons of stuff going on behind the scenes that I don't entirely know about. I want to know exactly what's going to happen when I program. I don't want magic, I want logic.
Also, rsc has a short article about the issues with generics here. I don't see anything that you wrote that addresses it.
Golang competes in the Java/C# space, not the C/C++/Rust space. It has a garbage collector. It abstracts things away from you. Even stack allocation isn't explicit. Its concurrency model is nice, but isn't as performant as raw threads can be since the runtime scheduler isn't free (this is why Rust got rid of its green threads implementation early on).
The consensus across the Go community is to use the net/http.
The standard library already offers a good set of features that you can leverage and extend by yourself. Some times. The most common approach is to include specialized packages as middleware to provide cache, routes, authentication, etc and avoid convoluted frameworks from early development. If you search the same question on the Internet and/or ask professional Go developers, you will get, most of the time, a similar answer.
Tweaking the GOGC
variable doesn't seem like the most prudent solution here. Not to mention it's a one dimensional knob, and another part of your code might work better with a different number so now you have to choose what part you're optimizing for.
Seems to me it'd be better to use object pooling in the specific instances where you know you're going to use a bunch of objects for short periods of times. Go comes with a simple implementation in the standard library.
> When it comes to Go, you don't know what you're talking about. Learn to write a container type and then get back to me. Here's a Heap https://golang.org/src/container/heap/heap.go?s=2105:2138#L51 See the return type? interface{}.
> This is how it's done in Go.
Markov Chains have been around a long time.
A guy I met at a computer training class showed me this project he did - collecting all of the "online (text) erotica I could find", then feeding it into in a markov chain text generator, and then hooking that up to the speech synthesizer. The computer generated filth that came from the machine was pretty amazing.
In order to deploy Go1.9 RC1 as the default inside Google, we do a significant amount testing to make sure the transition from Go1.8 to Go1.9 is as smooth as possible. Sometimes this means fixing regression bugs in the toolchain (e.g., https://golang.org/issue/21120, https://golang.org/issue/21121). However, oftentimes it means fixing brittle code inside Google that made unfounded assumptions about behavior of the Go toolchain that changed in Go1.9.
At the time that we cut RC1 it means that Google is not aware of issues (either in the Go toolchain or in the Go code at Google) that prevents RC1 from being production ready for Google. Now, to a degree it is reasonable to assume that the vastness of Google's Go code is a representative sampling of how the world uses Go, so regression bug discovered by Google also benefits the world. However, any sufficiently large code base may still use Go in a way that triggers a regression bug that did not affect Google.
I don't know if Caddy has a set of canaries that thoroughly test Caddy in a production setting with production-like load. If so, I recomment building Caddy with Go 1.9 RC1 and send it through the canary for a bit and make a judgement for yourself of whether Go1.9 RC1 is production ready for you.
My talk at GopherCon was essentially about this subject: https://www.youtube.com/watch?v=OuT8YYAOOVI
P.S. I mention above about the regression testing Google does, but I do want to acknowledge and thank all those who do regression testing themselves during the betas and RC1.
P.S.S. We're also heavy users of Linux, so we do rely on the community at large for discovering regression bugs for other GOOS.
No more easy to click navigation buttons! No more function over form! No more directly accessible licensing information in the footer (but hey, isn't https://golang.org/doc/copyright.html beautiful [and also mislabeled])! I can't wait for the redesign to hit the playground.
​
But hey, we do have a "Google" logo on the front page now, I guess Go is finally a project that Google is proud of?
> Arguable. I would say they are almost the same.
I'm a fanatic rustacean and I'd be very wary of describing the strengths of the language to newcomers in this way. Go's approach to stdlib and Rust's are day and night, it's a consciously-made, well-known design choice.
I feel a comparison of the form "it's basically the same except for X and Y" is a bit misleading and disingenuous. I don't have any significant Go experience, but just perusing through https://golang.org/pkg/ I can see support for data compression, random numbers, misc. data formats (json, xml, etc.), image processing, etc.
Personally, I try to explain that "Rust is a lean-stdlib language, for reasons X and Y".
> The lack of generics
That one I can't fathom. In 2012, they had enough hindsight under their belt to know that done right, generics are simple and make your life easier (unlike C++ templates). The official justification is weak. Adding generics later is bound to be more difficult. They shouldn't make the language much more complex (unless they insist on subtyping, maybe?) and the induced runtime complexity is definitely simple (Ocaml solved it with pointer tagging years ago).
What were they thinking?
Haha. I'll also plug one of my tiny crates: <code>tabwriter</code>. It provides a type that implements io::Write
and automatically replaces output with \t
in it to an aligned table padded with spaces. It's based on the package with the same name in Go's stdlib.
For high quality and idiomatic code, just check how the standard library is written. One can find plenty of inspiration there and it looks like very bright people maintain the code.
> D's site is an example for a great programming language site.
and python and go. Python is particularly a good example because it is bold, professional, and continues to draw focus on the most important aspect of the project, the language itself.
I don't know what unfortunate chain of events that lead rust to choose such an unfathomably poor design.
When you have a site that focuses more on the meta aspects of the language rather than the language itself, you know something has gone horribly, horribly wrong.
Dunno, I think Rust is a decent name.
Meanwhile, "Go":
• can be confused with one of the most common English verbs and short words in some other languages;
• is also a name of a several thousand years old board game;
• is also a name of another programming language that came out before;
• is so short that many search engines refuse to search for it;
• and it's all for sake of a pun that stopped being relevant before releasing the 1.0 version:
> What is the origin of the name?
>“Ogle” would be a good name for a Go debugger.
>Go versions prior to 1.0 included a debugger called ogle. This is named after a company named something like Go ogle that has funded a lot of the development of Go. This was not ready in time for the 1.0 release, so it was removed.
– The Go Programming Language Phrasebook by David Chisnall
Neat. It sounds like python suffers from the exponential search time problems that PCRE suffers from with pathological inputs.
Does using a DFA-based regexp engine such as RE2 or Go's regexp suffer from the same problem? I would expect not.
With those engines it shouldn't matter whether you collapse inputs from /(perl|python)/ to /p(erl|ython)/
Do not use map[string]interface{}
! Use a struct with fields of type <code>*json.RawMessage</code>. If you don't know the key names, use a map[string]*json.RawMessage
.
Oh? Like maybe Go or Python? Ruby?
I dunno about you, but I've seen some pretty toxic shit in C and C++ communities—which don't have a code of conduct. As far as I can tell, Haskell folk seem to do okay without one.
Do you feel like the code of conduct is holding you back in some way? Why do you care?
log.Fatal
, you should propagate errors up generally, and handle them appropriately. Probably just exiting, but still, it's good to avoid log.Fatal
ing in the middle of your code. defer
'ed functions do not run when you do this, which causes potential resource leaks (eg: if you create a tempdir, then defer the deletion of the directory).*Comic
, not take one.I'm doing a webserver right now only using stdlibs and I can affirm that the template parsing is easy to use and setting up routes are really easy. They even have a nice tutorial!
Author here. I spent a good hour debating & researching what to actually call "memory allocated things". I went with "object" because it's used numerous times in Effective Go and that seems to be the canonical reference in Go.
The Go Team recently added this page to the documentation website: https://golang.org/doc/editors.html as a comparison of the popular editors for Go. There are many other things each of them can do so try them out and use whatever makes you the most productive.
> it isn't obvious to me how to encourage a Go program to "run in parallel"
You use the <code>go</code> keyword. Go tries to avoid magic; your algorithm will not be parallelized unless you make it so. If GOMAXPROCS >= NumCPU
and NumCPU > 1
, you're likely to see a performance improvement when using the go
keyword. Last I heard, current Go versions will set GOMAXPROCS = NumCPU
so you generally won't need to adjust it.
> I don't see how concurrency can help me unless if I am using multiple cores.
Correct.
> In fact, I suspect that the overhead of the goroutines would slow me down if I am limited to a single core.
Correct.
> Am I making sense at all?
Your head appears to be screwed on straight.
The strings.Builder still has to take care of growing the backing byte array. You could pre-grow it if you can estimate the final size, that would make the code even faster.
https://golang.org/pkg/runtime/debug/#SetGCPercent
> SetGCPercent sets the garbage collection target percentage: a collection is triggered when the ratio of freshly allocated data to live data remaining after the previous collection reaches this percentage. SetGCPercent returns the previous setting. The initial setting is the value of the GOGC environment variable at startup, or 100 if the variable is not set. A negative percentage disables garbage collection.
So you would do:
debug.SetGCPercent(-1)
You can then trigger a garbage collection "manually" with:
runtime.GC().
It looks like the working group is listed here: https://golang.org/conduct
It's comprised of 1 Ardan Labs employee, 1 Stripe employee, 1 Canonical employee, 1 Clever employee, and 4 Google employees.
It's not clear how or why these people were selected. But they were pre-selected for the original proposal: https://github.com/golang/proposal/commit/7e7ce02d6e9cf7dfe90d03f4fce9984f04100d0d
To trabalhando com Go já faz uns dois anos, a linguagem vem crescendo muito, muito mesmo. Para fazer tools e microserviços ela é sensacional, e ainda temos o melhor mascote, o Gopher.
Alem disso minha OKR para esse trimestre é aprender Scala, mais para pegar conceitos de linguagens funcionais do que qualquer outra coisa.
Eu gosto muito de usar o GitLogs pra saber o que tá rolando pelo Github e tambem gosto muito no /r/coolgithubprojects
Qualquer coisa tamo ai! ^Go^é^muito^melhor^que^RUST
Well, there is the basic pkg provided by Go located here: https://golang.org/pkg/image/draw/
But if I recall correctly pixel is a pretty prominent one https://github.com/faiface/pixel if that is what you are looking for. Also GG https://github.com/fogleman/gg. :)
Have fun!
Cmd.start() will start a process but not block on it finishing. It will return a handle to the process which you can Cmd.Wait() to block the thread until that process exits. With this you can start the 20 processes, add their results to a slice then loop of the slice waiting on each process to exit.
This is a collection of bad ideas, founded on misunderstandings, wrapped in a rant that borders unreadable. I could nitpick all the little things, but let's just choose this:
> Go’s theoretical underpinnings are heavily based in Hoare’s CSP model, [..]
> As soon as you [...], bam, you’re no longer in pure CSP land.
Let's compare that with what the authors themselves say:
https://golang.org/doc/faq#ancestors > Go is mostly in the C family (basic syntax), with significant input from the Pascal/Modula/Oberon family (declarations, packages), plus some ideas from languages inspired by Tony Hoare's CSP, [...]
So, "heavily based" and "pure CSP" vs "some ideas [...] inspired by [...] CSP".
Go did recently acquire type aliases in the same sense as Rust's type aliases, in that they are purely syntactical aliases and do not correspond to separate and distinct types. Type aliases in Go (type Foo = Bar
) are not often used, and IIRC, the original motivation for adding them was as a tool for refactoring.
As far as I can tell, the OP is using "type alias" incorrectly in Go land. Type aliases in Go (type Foo = Bar
) have the same semantics as type aliases in Rust. The probable source of confusion is that since type aliases were added somewhat recently and rarely used, I believe folks have often referred to Go's newtype pattern (type Foo Bar
) also as "type aliases." But they are not aliases and are indeed new types (in type Foo Bar
, Foo
is a distinct type from Bar
). Go also has some additional rules around assignability that can blur this line a bit more, but usually Do The Right Thing.
In my experience, neither language really "wins" on this particular and specific front, but there are definitely some interesting differences in expressibility when it comes to encapsulation, which is something you often want to do with newtyping.
Apparently only float64s get the privilege of using Min https://golang.org/pkg/math/#Min
10xers probably figured out that no other number type could be large enough that you'd need to limit a value so need for it. Very pragmatic
Bonusjerk, second result for "go min function": https://mrekucci.blogspot.de/2015/07/dont-abuse-mathmax-mathmin.html
I can really see what gophers talk about when they say its limited feature set prevents huge classes of issues.
The http lib news up an instance of each type of error it will return and returns those. You can see here that the Cookie func will return the ErrNoCookie instance in the http package.
So you can check if it's a the cookie not present error by doing
if err == http.ErrNoCookie { // handle this specific error }
How can anyone claim closed source code is more well commented/documented than open source? There are literally no statistics. I've worked on plenty of enterprise projects that were 90% uncommented spaghetti code and I think anyone who has used .NET will say the same.
The best commented code I've ever seen is open source and it's the golang source code:
https://golang.org/src/net/http/server.go
Can you link to closed source code that's commented better?
The Tour is the canonical learning resource: https://tour.golang.org/
The codewalks are fun, and underutilized I feel: https://golang.org/doc/codewalk/
exercism.io is a fun site for practicing programming and getting feedback on your style. They have a strong Go track you can participate in.
The resource you are looking for is GitHub; you can readily find large, popular, well maintained projects there and see exactly how they are made. To get you started, Docker is considered a great example of high-quality go code.
To answer your questions more specifically:
For example, if you have a "Person" type with some methods, rather than having "Attendee" and "Guest" types that inherit from Person, you would have "Attendee" and "Guest" both embed Person, and thus gain access to all Person's methods.
What you're looking for is runtime.LockOSThread()
this will force the goroutine to stay on a single OS thread https://golang.org/pkg/runtime/#LockOSThread.
As for the same goroutine being used each time. I would have it setup to feed the goroutine work via a channel. That way your wrapper would pass work off to the goroutine that is locked to the OS thread.
It's right there in the FAQ.
Especially see the point 4 in the Splash article that FAQ entry refers to.
…and while we're on it, the language is called "Go".
I agree with larger "wishful thinking" point, but Go license does not force you to follow their code of conduct. It is standard BSD. Language specification and website documentation are licensed under the Creative Commons Attribution 3.0 which does not mention code of conduct either.
Rust is distributed under MIT license which does not references code of conduct.
With latest Go release, it is completely free of C code <link>. Even though it is mentioned rust compiler is written in rust <link>, Still g++/clang is a dependency <link>. Why is it so? Any plans to remove?
Hi
Just my thoughts
In the former case I needed interface{}
because the matrix was to store elements of the semiring, not the semiring interface itself. But even if it were to, I'd still need to explicitly cast to and from that interface, so as to get to the underlying value.
In the latter case I needed interface{}
because that's what the standard List
type does. Not much I can do about that, I'm afraid.
https://golang.org/doc/faq#semicolons
> Go uses brace brackets for statement grouping, a syntax familiar to programmers who have worked with any language in the C family. Semicolons, however, are for parsers, not for people, and we wanted to eliminate them as much as possible. To achieve this goal, Go borrows a trick from BCPL: the semicolons that separate statements are in the formal grammar but are injected automatically, without lookahead, by the lexer at the end of any line that could be the end of a statement. This works very well in practice but has the effect that it forces a brace style. For instance, the opening brace of a function cannot appear on a line by itself.
>In Go, function and method calls are the primarily, perhaps only, mechanism of abstracting computational complexity. That is, when you see a function or method call, you know that "anything goes" back there, and you need to dig and find out what the computer is gonna be doing.
>cast is linear in number of methods on target interface, except when it's not, because cache
>unspecified memory safety breakages
>compiler depends on Unicode's black boxes when language is supposedly meant to be manipulated by third party tools
Goroutines don't have parents or children. When you start a goroutine it just executes alongside all other running goroutines. Each goroutine exits only when its function returns.
The only exception to that all goroutines exit when the main goroutine (the one that runs function main) exits. (There is also <code>runtime.Goexit</code> which has limited use.)
A few things here:
The examples are actually racy. If you run it with the race detector, it'll complain. So… don't do this :) The stdlib example notably uses atomic
, to make the accesses race-free.
You should really just use sync.Once, that's what it's for and it does the correct and performant thing under the hood already.
If you look internally at the implementation of ToLower it has to create a new string builder and then append characters to it, then return the resulting string. That means ToLower needs to return a thing that has a pointer to a dynamically sized buffer, so it must be heap allocated. If ToLower were just mutating the input string then it may be possible to avoid any heap allocations.
You could have just written it down. It just wasted 5 min of my life. He just talks about this:
func f(ii ...int);
ss := []int{0, 1, 2, 3, 4} f(ss...)
Found the official comment confirming your experience: https://golang.org/doc/faq#inheritance
“It takes some getting used to but this implicit style of type dependency is one of the most productive things about Go.”
Having Write()
return (int, error)
allows string.Builder
to be used as an <code>io.Writer</code>. Explicitly documenting it to return nil
allows callers that know they're specifically using a string.Builder
to elide error checks.
This doesn't feel like an ideal solution, but at a minimum bytes.Buffer
does the same thing, so at least there's precedent.
The correct syntax to do this is
func doSomething() [][]int {
}
For further informations, read Effective Go: Two-dimensional slices.
Also note that this a slice of slices, not an array of arrays.
There are a lot of open issues at https://golang.org/issue. Fixing those, or determining that they can be closed, would be very helpful.
The documentation is good and steadily improving, but where you see problems please send fixes or open issues.
At the more advanced level, there is plenty of room for improvement in the compiler, and this is an area where many people can usefully contribute. For example, somebody asked about debug info above--this is mostly a compiler and linker issue.
Have you read How to write Go code on the main site? It doesn't touch on modules yet but I think it covers what you're looking for w.r.t packages and directories and files and import paths.
> Can you point me to a go based REST service that is good example of the proper level of abstraction in Go?
No language dictates a "proper level of abstraction." Build what you need to build and abstract when the simplest form of your implementation becomes heavier than the abstraction would be. That's as true in Go as in anything else.
If you're interested in Go-specific best practices, I'd recommend reading Effective Go.
Well yeah it does not try to follow the SSH protocol in any way :)
​
It does vendor golang.org/x/crypto which i believe does - and then have a few hacks applied to it
No GitHub doesn't prevent projects from being deleted.
Depending on the license of the open source libraries you are using, in most cases vendoring (and don't put vendor
to your .gitignore
file) is the way to protect against the concern you have here.
As someone who also came from C++, I agree, go get
is one of my favorite features of Go too.
If you have your Go package hosted on a code host like GitHub or any other, you should be able to use go get
on it.
The following document describes the process of writing some Go code to make Go packages, and then making it available for go get
:
https://golang.org/doc/code.html
It describes the whole process from start to finish. This section is most relevant to what you’re asking:
https://golang.org/doc/code.html#Library
There’s also a screencast version mentioned in the introduction.
If you want more of a reference on how go get
resolves import paths, see https://golang.org/cmd/go/#hdr-Remote_import_paths.
I hope you enjoy!
actually, this is hilarious. Have you looked at the source code for concatstrings? It literally has a for loop. So, when you're adding multiple strings together on the same line... dramatic drumroll there's a hidden for loop!
> Objects, arrays, values, types, methods “feel similar”
Fail.
> tunable data layouts
Fail, AFAIK.
> Shared code mechanically customized to each hot path
Fail, AFAIK. Cases when compiler successfully inlined the code don't count: that's not shared code.
> Confined/immutable data
Fail, AFAIK.
> Robust integration with non-managed languages
Success.
> Safely and reliably runs most modern languages
Fail.
> Runs 30-year-old dusty JARs
Fail: https://golang.org/doc/go1compat.
> Gets the most out of major CPUs and systems
Requires at least beating Java today, which Go doesn't always. Still, a partial success.
Corrections welcome.
There is no advantage, the reason the author suggested that is because he has not properly read the documentation for "crypto/rand".Read, which states: "Read is a helper function that calls Reader.Read using io.ReadFull. On return, n == len(b) if and only if err == nil. ".
Typically, types that implement io.Reader can read less than len(b) without error, if that were the case for "crypto/rand".Read, then calling it to fill a buffer with random data might end up only filling part of that buffer with random data, leaving the latter part zero.
As you can see from the implementation of "crypto/rand".Read, it handles that potential mistake for you by wrapping the call to the underlying reader with io.ReadFull:
https://golang.org/src/crypto/rand/rand.go
// Copyright 2010 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file.
// Package rand implements a cryptographically secure // pseudorandom number generator. package rand
import "io"
// Reader is a global, shared instance of a cryptographically // strong pseudo-random generator. // // On Unix-like systems, Reader reads from /dev/urandom. // On Linux, Reader uses getrandom(2) if available, /dev/urandom otherwise. // On Windows systems, Reader uses the CryptGenRandom API. var Reader io.Reader
// Read is a helper function that calls Reader.Read using io.ReadFull. // On return, n == len(b) if and only if err == nil. func Read(b []byte) (n int, err error) { return io.ReadFull(Reader, b) }
Go has almost 900 contributors, most of which are not Google employees. https://golang.org/CONTRIBUTORS
Thus far contribution acceptance seems to be much more merit based than politically motivated. Google does push for support for their initiatives (such as HTTP/2) but I haven't seen any evidence of a contribution being declined for non-technical means.
Just as many people consider unique_ptr sufficient, I found many people consider something like ThreadSanitizer and Go's Data Race Detector sufficient. These people don't deny that Rust's guarantee is stronger, but they think it doesn't matter much in practice.
This is a good question and I don't have a short answer.
Programmers new to Go often use channels way too much or way too little. Some misunderstand slices--https://golang.org/blog/slices is a great resource. It takes a while for people to understand how and when goroutines terminate. People often don't realize that close on a channel is not necessary, and that it is purely a send operation.
:=
also (re)declares variable(s).
v1, v2, v3, ..., vI, ..., vN := x1, x2, x3, ..., xI, ... xN
At least one of variable vI
must be new.
https://golang.org/ref/spec#Short_variable_declarations
x := 1 // var x is declared x, _ := a, b // no variable is declared. Hence compilation error. x, err := a, b // var err is declared. x is overwritten.
> Redeclaration does not introduce a new variable; it just assigns a new value to the original.
Yes, interface{}
is what I'm thinking of.
> For example, a logging framework could accept []io.Writer, a list of values that implement the io.Writer interface, and safely write to each one without requiring a cast.
Yep, Java has Interfaces, too. It had them before it had generics. They solve a different problem.
> ...when you're trying to build a custom data structure that needs to be as generic as possible...
Not even "as generic as possible." I'd settle for "won't make me search-and-replace when I need to switch 32-bit ints for 64-bit."
It's not just data structures, it's algorithms. In Java, the function signature for a sort is one of these:
void sortComparables(List<T extends Comparable<? super T>> items); void sortWithComparable(List<T> items, Comparator<? super T> comp);
How would you express that in Go?
Again, Go's answer is "It's built-in. You don't have to write a sorting algorithm, because we, the language gods, who are allowed to use generics, have written a sorting algorithm for you." Okay, fine, but what about a priority queue? Here's Go's answer to that. It's not even a data structure, it's just some generic heap-sorting algorithms for working with an array. Of the five functions provided, one is a constructor and three use interface{}
, and are thus type-unsafe.
And that's in the standard library! That's actually how they expect Go programmers to solve this problem.
Because making it actually typesafe would be too complex, I guess? Admittedly, those function signatures are pretty complex. But it takes a lot less work to understand that than to deal with runtime type errors.
Edit: And I find it hard to express how sad it makes me that I'm defending Java. I really don't like Java. I just find it mind-boggling that Go can be missing this truly basic shit that Java has, and they're missing it on purpose.
This would violate Go's own guidelines:
> Do not store Contexts inside a struct type
"Carrying" a context around is code smell, since the caller isn't aware of what context will be used. Something may create a FS object and store it in a struct itself, and now it has some arbitrary context that must potentially be overridden (with this hypothetical WithContext
) on every single call. For example:
type Worker struct { fs fs.FS }
func NewWorker(fs fs.FS) *Worker { return &Worker{fs} }
func (w *Worker) DoSomeTask(ctx context.Context) { fs := w.fs.WithContext(fs, ctx) // Needed to use w.fs
file, _ := fs.Open(...) // OK!
w.doMoreWork(ctx) }
func (w *Worker) doMoreWork(ctx context.Context) { w.fs.Open(...) // Potential bug: Wrong context! }
If this new FS
interface is to support contexts, every potentially blocking method should take a context if we are to follow the guidelines. That's unfortunate; I personally don't like contexts because how they are "viral", requiring the context to be explicitly passed through the entire chain of calls. But that's how they're designed.
What verbose? Error checking is just a if err != nil {}
away!
​
It saddens me deeply that there are still people who can't even begin to appreciate the sheer genius of Rob Pike aka import
<code>golang.org/lol/no/generics</code> and the beautiful alternative version of CTRL-C driven development the language proposes.
> Go is better
Oh no. Go is not better. I've tried porting Go to FreeBSD/aarch64. Go is terrible for portability. The "use syscalls directly" approach requires huge effort to port to a new platform. The custom assembler is just bad.
> What are some standard practices of writing a http server in go?
https://golang.org/pkg/net/http/#ListenAndServe
> How should I proceed with tests and define project layout?
https://golang.org/doc/code.html#Workspaces
> Is there any package management tool for go like NPM for Node.js?
https://github.com/golang/go/wiki/Modules#quick-start-example
There are a lot of reasons to like Go, but the multithreading and concurrency primitives are definitely up there.
This code snippet gets thrown around from time to time, but it's one of the most beautiful examples of what can be done with the language.
An interface variable has a dynamic type and a dynamic value. It is nil only if both the type and value are nil. In your case it's got the type *main.S and the value nil (use reflect TypeOf & ValueOf). Try printing it before assigning it to s.
b1 := []byte { 1, 2, 3 } b2 := "string"
b1 = append(b1, b2...)
fmt.Println(string(b1))
Depending on what you try to do, you might be better of with a bytes.Buffer though.
edit: removed unnecessary cast :)
You should actually use "stream decoding" as described here: https://golang.org/pkg/encoding/json/#example_Decoder_Decode_stream
If your JSON file is "well formed" (i.e. your entries are part of a big JSON array) you may need to skip the initial "[" and the "," between entries.
https://golang.org/doc/faq#What_is_the_purpose_of_the_project
It was made specifically to supplant C/C++ and Java. For exactly the same reason that Rust was made to supplant C/C++: the creators don't like coding in C.
No one is under any illusion that Google and Mozilla are both attempting to make the next standard in OO languages.
Build tags are a good solution here. Easy to have a logging implementation that makes debug logging a no-op for a production build. having two files: log_debug.go and log_debug_production.go
You probably mean "in the standard library", because the language specification is this document: https://golang.org/ref/spec It does not talk about the packages and functions of the standard library.
The lowest level of functions are system calls. They are calls to the operating system kernel. The system calls needed by Go are exported in the syscall package: http://golang.org/pkg/syscall/
However, most of the runtime functions are not exported, only a few: https://golang.org/pkg/runtime/
Found it:
https://golang.org/ref/spec#Arithmetic_operators defines negation as 0 - x.
In 16 bit signed arithmetic, 0 - (-32768) = 0 + 32768, which overflows back to - 32767.
Turns out its not a special case, just a natural consequence of how things work.
It's the channel receive operator, also used for channel send statements. Essentially it's data moving across a channel in the direction the arrow is pointing.
La Grue Cendrée (source on github) is a pixel art map generator and a work in progress.
Help!
I am not a designer or graphical artist of any kind, so if any one has any idea as to how to draw cities, villages or castles or other landmarks, I’m open to suggestions. Also it would be nice if these could be generated as well instead as just drawn and pasted on the map.
How it works
The terrain (shapes of islands and ocean) is generated first. Each cell (above image is 400×200) has an integer value, positive meaning island and negative meaning ocean. Then comes in the MAGIC
variable, equal to 2*sqrt(HEIGHT+WIDTH)
(because it seems to work this way). In the beginning there are MAGIC
cells set at a value of MAGIC
, the rest at 0, and the picture evolves over MAGIC
frames. Basically, at each frame each cell can do one of three things:
(Edit: exchanging also changes the values of the current and exchanged cells, and terrain evolves this way.)
Then features are added:
Future changes
Programming
Its written in Go without any external libraries.
Conclusion
Thank you very much for viewing, upvoting, reading, etc. If you have any question, suggestion of feature or colors or anything, please do leave a comment!
Edit2: typo
The book is well worth it. Also, regarding the versions, the current version of Go is 1.12.5 not 12.5. Go 1 spec guarantees compatibility of Go 1.x releases (see https://golang.org/doc/go1compat)
How about building `a` out of the real part you have and the imag part of `a`?:
https://golang.org/pkg/builtin/#complex
```
a = complex(2 * real(b) + 1, imag(a))
```
The Go code fmt.Println(1, 2, 3)
prints three numbers. The code certainly is quite readable, but not so transparent. It is not clear if the time complexity is constant or linear.
Hint: it's linear
Why is this even an argument if the Go standard library uses for loops everywhere? Any function application looks like O(1), but sometimes it's actually O(n). If gophers weren't so hypocritical, there wouldn't be any for loops at all in the standard library.
This is going to sound harsh, but what’s up with the easy-to-google questions?
If you visit the official website https://golang.org/ you’ll see a yellow-ish panel where you can type code, and execute it online. It has buttons to “Run”, “Share”, and to visit the “Tour”. Then, if you click the “Pop-out” link in the top-right corner of that panel, you will be redirected to the official Go Playground — https://play.golang.org/
This is very passive aggressive, but please read this: http://www.catb.org/~esr/faqs/smart-questions.html
That's not strictly true. You can mutate errors (or slices of them or whatever) in the defer. Often people ignore the error in close as there is little you can do. You can read more at https://golang.org/doc/effective_go.html#defer. But even if you don't use defer, you should make sure after a successful file open/create, you ALWAYS attempt close the file regardless of code path, which you are not doing on failed write.
Also, do you notice you are doing things in later examples like calling fmt.Fprintln
without checking if it failed at all? There are lots of mistakes in your post.
>We believe that coupling exceptions to a control structure, as in the try-catch-finally idiom, results in convoluted code. It also tends to encourage programmers to label too many ordinary errors, such as failing to open a file, as exceptional.
To sum it up: Developers tend to throw exceptions too excessively. Errors are natives types in Go. The design forces you to handle them more explicitly. See the following example:
package main
import ( "os" "fmt" )
func main() { f := os.Open("filename.ext") fmt.Println(f) }
os.Open
returns an error as the second return value. This won't even compile since two values are returned. In contrast to an exception that occurs when it's maybe too late and you don't have to catch. To make it compile again, handle the error or use the blank identifier f, _ := os.Open("filename.ext")
.
> Golang where cancellation is usually managed through manual object passing and convention, or (even worse) one that doesn't have a generic cancellation mechanism.
https://golang.org/pkg/context/#WithCancel
Of course, requires the users of context to check the done channel. Also, Go sucks on generics too hard to support task wrapping. You can't build a reasonable "nursery" library without casting everywhere. You just have to use https://golang.org/pkg/sync/#WaitGroup to wait until they are all done and accept not having things like easy returnes from goroutines.
It's known that Go purposefully chooses to suck on a lot of features on purpose. These are not out of ignorance but choice. No need for a blog post on every design decision they made.
From https://golang.org/pkg/encoding/json/
> The Go visibility rules for struct fields are amended for JSON when deciding which field to marshal or unmarshal. If there are multiple fields at the same level, and that level is the least nested (and would therefore be the nesting level selected by the usual Go rules), the following extra rules apply: > > 1) Of those fields, if any are JSON-tagged, only tagged fields are considered, even if there are multiple untagged fields that would otherwise conflict. > > 2) If there is exactly one field (tagged or not according to the first rule), that is selected. > > 3) Otherwise there are multiple fields, and all are ignored; no error occurs.
Not sure why we need yet another "Getting started" tutorial. The official documentation (Getting Started, A Tour of Go, Effective Go, etc.) is beginner friendly enough as-is.