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)
I call it Go, but usually google for ”golang”. As the term ”go” is un-googleable. Dont know what the fuzz about, no one thinks the language is actually called ”golang”. In the same way racket is usually called ”racket-lang”, hell, even their domain is https://racket-lang.org/
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.
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.
Everything is a trade-off, there is no "best" language. On the other hand, here are some trade-offs I see:
parseInt
does not return an integer despite documentation lying to your face and saying that it does. Proof: parseInt("-0")
does not return the integer 0
.)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.
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.
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.
Designing Data-Intensive Applications seems to be the industry standard, although it's not Go specific.
> Are there any IDEs you would reccommend that is in a more stable place?
Visual Studio Code + lukehoban.Go
extension (Marketplace)
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?
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.
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
.
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.
You have plenty of options:
Aside that... how much are you... developers... earning? That you see this price, once a year, as expensive?
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
My favorite commentary on this is from a newsgroup post by Elizabeth Rather, who explained Chuck Moore's (inventor of Forth) "Axiom on the conservation of complexity" like this:
> Any given problem has a certain intrinsic level of complexity. In the solution of the problem, this complexity will be conserved: if you dive in with too little advance thought, your solution may become very complex by the time it's done. On the other hand, if you invest more in thought, design, and preparation, you may be able to achieve a very simple solution (the complexity hasn't gone away, it's become embodied in the sophistication of the design).
It's actually very difficult to make something that is as simple as Go as expressive as Go manages to be. That simplicity has a cost, but that cost is not part of implementation complexity, that cost is embodied in the decades of experience that went into understanding what was necessary and what was not.
There is a similar, perhaps apocryphal story, about a great veteran logo designer. A young business owner meets the designer at a cafe to discuss a possible job designing a logo for their new business. The designer then scribbles out the perfect logo, elegant yet sophisticated, on a napkin in a few minutes.
The business owner asks the designer how much it would cost, and the designer quotes her something outrageous. "It only took you a few minutes!" The designer explains that she's used the sum total of decades of experience to create a design that was elegant, unique, would look good large or small, through many generations of faxing and photocopying, in full color or black and white, etc. The fact that it took very little time and looked simple belied the depth of thought that was called upon.
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".
Well I disagree with you both! :-)
The golang style guide provides excellent advice in this regard..
> the further from its declaration that a name is used, the more descriptive the name must be
IMO overly verbose variable naming makes it difficult to skim a block of code to figure out what it's doing.
This is not uncommon advice - see also the Linux Kernel style guide, for example.
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 }
Channels are usually best understood as implementation details, and not part of a package, component, or function API. So, using channels in function signatures, or returning channels as return params.
Channels must be owned, and closed, by a single entity. So, trying to share ownership and lifecycle responsibilities between functions or goroutines.
Adding a capacity to a channel turns it into a buffered queue. In general, queues solve precisely one problem, which is burstiness; using a buffered channel when you're not solving burstiness is usually an error. (Exception: you can use buffered channels to implement various design patterns, like scatter/gather or semaphores.) Buffered channels also have a tendency to hide design errors that would be immediately apparent if the channel were unbuffered. By default, channels should be unbuffered. If you add a capacaity, you should be able to justify precisely why you chose the number you chose.
Complex numbers aren't used that often:
c1 := 3 + 4.2i c2 := 0.5 + 5i c3 := c1 + c2*c2
New number literals since Go 1.13:
0x1.0p-1021 0x_A_.d_bp8i
Anonymous interfaces other than interface{}
:
func F(x interface{A(); B()}) { }
Full slice expressions (the max
part):
a[low : high : max]
Buffered channels (most people use unbuffered channels):
make(chan int, 2)
The bit clear operator:
a &^ b
Keyed items in array initialization:
a := [...]int{1, 10: 2, 3, 25: 5, 6}
Method expressions:
var p, q Point
p.Add(q) // Can also be written as: (Point).Add(p, q)
Function types can have methods (like all types, of course):
type MyFunc func(int) bool
func (f MyFunc) MyMethod() { }
Switch cases with expressions:
t := () switch { case t.Hour() < 12: fmt.Println("Good morning!") case t.Hour() < 17: fmt.Println("Good afternoon.") default: fmt.Println("Good evening.") }
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.
Hi
Just my thoughts
Except for all the Docker stuff, this is how Caddy started. Then I wrote a for
loop that "compiled" middleware from a []func(http.Handler) http.Handler
value. It still basically does this today, and is some of Caddy's oldest code.. (The outer loop builds the middleware stack for each site on that listener, or 'group' of sites.)
Then it was time for handlers to return errors, so that error handling could be more easily coordinated among dynamic middleware stacks. So I modified the http.Handler interface to return <code>(int, error)</code> values. A simple change, but by far one of the most profound effects on Caddy: it became easily extensible, and with a simple convention, balanced correctness and usability.
Caddy doesn't use third-party middleware packages or routers. Building it all from the ground-up with the Go standard library was a lot of fun.
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.
Looks cool! One thing to consider would be basing the protocol on something designed for network tunneling like Wireguard and contributing a go userspace implementation of it. You'll likely see much faster speeds and hopefully inter-operate with many other implementations of wireguard moving forward. https://www.wireguard.com/ There is even a standard UI spec for implementing userspace wireguard: https://www.wireguard.com/xplatform/
Possibly one of the reasons your seeing slow linespeeds is that TLS really isn't designed to be a network tunnel as it uses TCP. This means for many connections you'll be using TCP encapsulated in TCP which will create performance issues. Sorry if you already know all this!
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.
I can't really give you an unbiased opinion, as I loathe Node.js and its event driven madness. But I can tell you that Go's use of CPU cores is leaps & bounds better, seeing as Node isn't multicore. Not to mention Go will be quicker than Node in many other ways, too.
The thing you really have to ask yourself, is this worth the cost of a rewrite + learning a new language & its idioms?
My experience is that it was definitely worth it, but those three months of not adding value to my business was hard - but now that I'm on the other side of it I'm very very happy I made the change. However, I like Go's clean syntax & idioms so YMMV.
Maybe you should just implement clustering into your project?
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.
I wouldn't put too much trust in this, though a lot of programmers seem to. This index is based on popularity but I found it silly that it ranked Go so low (#122 in May 2015) when Go was popular. Now when its ranked higher, I haven't changed my opinion. It seems arbitrary and no serious person should base their decision on which language to learn or choose for a project based on this.
If you're a programmer, you should either look at what offers the most jobs or what's fun to use (depending on the programmer). If you're a tech lead you should look at other trade-offs like resource footprint, tooling, development time or ease of hiring developers.
If you're looking for the general opinion of programmers, you're still better off ignoring TIOBE and looking at the StackOverflow survey (2015, 2016).
> 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.
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.
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!
> JavaScript has NPM You have got to be kidding me... https://www.slant.co/options/4234/alternatives/~npm-alternatives
But seriously, the go package managers that you make reference to are all candidate implementations, the go maintainers go to great lengths to pick the right solution. This means lots of trial solutions spring up first and then one eventually wins or the learning from all those trials go into the official builtin solution. That solution is gomodules. It's still pretty new so you'd be forgiven if you hadn't heard of it.
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.
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.
You* can try this book - Distributed computing with Go.
After a brief intro into testing with Go and other such stuff, it explains how goroutines & channels work under the hood then shows how to use them. And rest of the book is about using these concepts with networking applications etc.
I've been taking Andrew Ng's Coursera course for Machine Learning. It is very good for people who aren't too adept at math and really explains a lot for a beginner.
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.
> "If Error": { "prefix": "e", "body": [ "if err != nil {", " $0", "}" ] },
It took me two seconds to realize this is the proprietary syntax to create a “Code Snippet” in Visual Studio Code [1].
Since no every Go programmer uses Visual Studio Code, you could have said something like this:
> “Maybe a code snippet will help the try() people out […]”
[1] https://code.visualstudio.com/docs/editor/userdefinedsnippets
Holy smokes; I just read a group thread linked in multidimensional array issue.
How people get through life being so abrasive is beyond me. (John Nagle)
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 :)
These implementations don't quite work, as described in the issue. This will round 0.5 to 1 (and -0.5 to -1) which probably isn't what's intended.
This is probably why the proposal was accepted. There are lots of edge cases and it's easy to have mostly working versions which are still subtly broken.
Edit: See https://www.cockroachlabs.com/blog/rouding-implementations-in-go/ for more info. My explanation wasn't completely right. This implementation will also round things like 0.499999999999999999999994 to 5 as well.
I ran into this blog post titled How a complete beginner learned Go as her first backend language in 5 weeks a while ago. It's both inspirational and has a great set of resources for getting started (though most already mentioned here).
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.
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
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.
The PostgreSQL "text" and "varchar" column types require their data to be valid in their configured character set; encrypted data is by design indistinguishable from a random sequence of bytes, and so is unlikely to be valid in any given character set.
Use a column with the bytea or blob types instead.
I've used both of these libraries while working with Elasticsearch for ~1 year and I settled on using github.com/elastic/go-elasticsearch/v8
I went with the official client because it seemed safer from a security perspective. The company is going to have their own security guarantees which you won't get from the olivere client.
To learn how the client worked, I spent a lot of time reading Elasticsearch's documentation and figuring out what I wanted to do based on that documentation. After you know what you want, I then translated it into the Go code.
I found both libraries do not do a great job of making Elasticsearch functionality "discoverable". It also wasn't easy to try new things once you knew they existed with the libraries. Eventually I discovered Kibana on Elasticsearch's cloud offering, which has an interactive online IDE I highly recommend. I ended up designing most of my queries in that IDE with my test data in Elasticsearch's cloud and then translating that query into Go when I was happy with it. That process had the shortest dev loop time and I loved how relatively easy the cloud offering was for setting everything up. But it's definitely not free - I think I spent ~30 bucks a month.
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))
```
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")
.
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.
You should use something like Vault.
Failing that, you could make a script that populates your .env with a CLI tool:
https://1password.com/downloads/command-line/
Storing the secrets on disk, however, dramatically increases the risk of exposure, so I would strongly recommend having separate dev credentials and documenting how to invalidate them in an emergency and making sure you have monitoring on anything they could be used for. Or, you know, set up vault.
~~With the example in the link yes, you have to.~~ (EDIT: This is not true after all, see /u/bradfitz's comment below. If you have multiple certs, keep reading). But you can just use your own TLS config and implement GetCertificate. For example, we have a service at work that manages multiple Let's Encrypt certificates that can be renewed/revoked at runtime without restarting the server. Something like this:
var ( manager *certManager )
type certManager struct { lock *sync.RWMutex certs map[string]*tls.Certificate defaultCert *tls.Certificate }
func init () { // Get certificates from shared storage // and populate cert manager }
func GetCertificate(hello *tls.ClientHelloInfo) (*tls.Certificate, error) { manager.lock.RLock() defer manager.lock.RUnlock() if cert, ok := manager.certs[hello.ServerName]; ok { return cert, nil } return manager.defaultCert, nil }
This way, you never have to restart the server to add/remove/renew certificates.
quitComputeHash can be replaced with a sync.WaitGroup. You can call
wg.Add(nthreads)
when setting up the hashing goroutines,
wg.Done()
at the end of each worker, and
wg.Wait()
when waiting for the workers to finish.
In addition, the for-select at the end can be replaced with just a single receive as it will block the main goroutine until quit either receives a value or is closed.
Other than that, it looks good.
> False. It's deliberately defined to be unpredictable.
Let's look at the spec, authoritative source for the language definition of go:
> The iteration order over maps is not specified and is not guaranteed to be the same from one iteration to the next.
The segment you quoted is specific to the implementations provided by the go team. It's not part of the language spec. [edit: I even think that sentence just means it's defined to be unspecified - unpredictable doesn't mean randomized]
> It's not an implementation detail of gc. It's a deliberately added randomization.
The two aren't mutually exclusive.
> Don't call someone out on "not the right answer" when you don't know what you're talking about.
a) I do, and b) the answer is wrong regardless of the specification of the iteration order of maps.
[edit] To prove my point: The iteration order of maps in GopherJS is deterministic. Other implementations can choose any iteration order they like (that's pretty much the benefit of having it undefined)
You could use that, remember you can load the data from json easily also! Don't have to recompile anything again, just update the json file. Restart the program or write a reloading logic! Take a look here https://golang.org/pkg/encoding/json/
Hope that helps!!!
Hmmm, I venture you're not a programmer. (How did you get put into a situation where you need to run .go files?)
You need to install Go and then use cmd.exe with one of these: go build
or go run
or go install
. This converts them to a .exe file.
> Builds in Go 1.5 will be slower by a factor of about two. The automatic translation of the compiler and linker from C to Go resulted in unidiomatic Go code that performs poorly compared to well-written Go. Analysis tools and refactoring helped to improve the code, but much remains to be done. Further profiling and optimization will continue in Go 1.6 and future releases.
Sounds good to me!
sudo
will clear the environment for security purposes. You can ask it via -E
to preserve the environment. See man sudo.
But if you are running your app as a privileged process only for the purpose of binding to a privileged port (<1024) then you should consider giving the program the CAP_NET_BIND_SERVICE
capability to allow it to run unprivileged but still be able to bind to ports below 1024. See this answer on StackOverflow.
Insightful article. I really don't like this kind of hack, but I guess in the standard library it makes some sense, as it's used by everyone. Wouldn't care to see it in application code though.
> Reference types like maps and channels, like pointers, are considered to be the same if they have the same address.
I'm not sure this is correct wrt maps. Per the Go spec, "Slice, map, and function values are not comparable." However, channels equal if their addresses are equal: "Channel values are comparable. Two channel values are equal if they were created by the same call to make or if both have value nil."
In a weird turn of events, this coincided with the release of "Generative Art in Go" on Product Hunt. For whatever it's worth, the book that you guys motivated me to write is (hopefully still) on the front page of PH!
Thanks for all the support during the writing and editing process! You rock!
No it's not.
There is nothing stopping you from crafting requests with appropriate payloads and using the http ResponseRecorder to determine the outcome. https://golang.org/pkg/net/http/httptest/
There is no need for a "controller" in a web service.
If you are doing a web site, just do an SPA which hits services on the back end for the data it needs. It's far simpler and way less code.
EDIT: I have taught hundreds of java and python developers how to write idiomatic go services. Most refactoring that I've done of their projects entailed stripping away 85% of their code as it was completely superfluous to the function of the services.
If a type implements fmt.Stringer, Go will use that instead of the more raw forms, at least when told to print as a string (%s) or when not told how to print it (fmt.Println(thing))
In the case of big.Int, Int.String() calls Int.Text(10), which does what you'd expect.
CPU caching and prefetching is very, very fast, so my naive guess would be that slices are much faster.
Other people seem to agree: https://groups.google.com/forum/#!msg/golang-nuts/mPKCoYNwsoU/tLefhE7tQjMJ
If you feel like it, you could abstract the underlying container away(list/slice), and then compare both in a benchmark ;)
> is it a feature ?
Yes. By definition, "blocks nest and influence scoping"
> does this have any real-life use ?
I believe this question has only opinionated answers. In my opinion, extra scope blocks can be confusing to the reader and therefore might cause more harm than good.
If you need an extra scope block within a function, your function might be too large. Refactor the block into an extra function (and give it a meaningful name).
There is not an easy way to do streaming gRPC between a JS web client and Go server (edit: this may be wrong - see below.)
You might start by assuming you only have a single server, not a replicated game server. Once that is working, you can expand to many servers (ideally as needed).
To get your feet wet with the server aspect, send input through a form or plain URL parameter and return output in the body of the response. Check out this tutorial for using the vanilla Go HTTP server to create a simple site: https://golang.org/doc/articles/wiki/. Note, this essentially uses the filesystem as the database.
Ideally, the I/O should be isolated from your game logic (by functions and/or packages). This is good design in general, but would let you keep both versions of your game.
Once this is setup, you can switch to using websockets to make updates for clients in real time. If you're feeling impatient, you could go straight for this option. The gorilla websocket library is nice to use.
Become a go contributor: https://golang.org/doc/contribute.html
Seriously, reading the std lib will make you a better Go programmer, and picking up issues and solving them will force you to read the std lib.
Answer: size classes.
When Go allocates objects it tries as hard as possible to allocate using a size class
So, let's look at what happens in the int
version:
Now look at the byte
version:
I had originally written a slightly nastier comment earlier, because the algorithm is wrong. The byte
example is the technically correct answer.
If instead of passing in an empty slice, pass in a make([]T, 0, 4)
and you can quite easily see where the algorithm goes wrong.
I should add that the relevance to /r/golang is that devd is written in Go. In fact, this is the first Open Source project I've released in Go, after a long-ish career writing things in Python (e.g. qtile tiling window manager, mitmproxy interception proxy, and so on). At this point, I suspect my next project will be in Go as well!
Actually, sessions are a bad practice when facing a REST API.
REST is / should be stateless. Meaning, every request should be able to identify themselves after an authentication happened.
Either via access_tokens in the header, or via Bearer - Tokens, SSL and OAuth 2.
Having a session really defeats the purpose of having a REST implemented.
$0.02.
If it's HTTP 1.1 it should be case insensitive, so instead of making workarounds, pestering Amazon to fix it would be the "correct" way to handle it.
> I'm not pay 400€/year for the full blown IntelliJ package just to have both ECMAscript and Go editing.
I know very little about GoLand, but their website says it supports JavaScript:
> The IDE inherits from WebStorm its first-class support for front-end languages and frameworks. The IDE offers top-notch coding assistance for JavaScript, TypeScript, Dart, React and many others. The support for Angular and Node.js is available via plugins.
He mentions it in the article: There is a builtin println
function, but that prints to stderr
instead stdout
. Also there is no guarantee for that function stay in the language, so you probably shouldn't use them: https://golang.org/ref/spec#Bootstrapping
The spec says:
> The method set of the corresponding pointer type *T
is the set of all methods declared with receiver *T
or T
(that is, it also contains the method set of T
).
This rule could be read as applying to arbitrary layers of indirection, or it could be read as applying to a single layer of indirection.
Automatic double-dereferencing is now considered a bug and was fixed in Go 1.4, indicating that the second interpretation is correct.
If this change broke your code, dereference once using *
(thus converting **T
into *T
) and call whatever methods you want.
If all you're worried about is passing a type which is not expected, you can define an interface like
type handler interface{ isHandler() }
and then have Handle
take a handler
and have all the relevant types implement isHandler()
.
You might also be interested in: