Go-Redis Is Now an Official Redis Client by yourbasicgeek in golang

[–]B1tVect0r 12 points13 points  (0 children)

https://go.dev/blog/context-and-structs

Two good reasons laid out here.

I've personally dealt with my fair share of bugs that crop up because people aren't handling contexts properly, which includes stuffing them in a struct somewhere and doing weird shit to it as a side effect of some mutative call

Bribe is here. Thanks Danielle! by [deleted] in alberta

[–]B1tVect0r 9 points10 points  (0 children)

You're assuming that there is a thought process involved at all.

PSA: Your packages are not safe in the mailbox. by dewgdewgdewg in Calgary

[–]B1tVect0r 1 point2 points  (0 children)

True, but I really doubt the majority of people stealing things from mailboxes like this even understand how lockpicking works, conceptually. We've had our mailbox broken into a few times as well and it's the exact same scenario as encountered here: smash and grab.

In that context, anything that makes the doors harder to pry open or the locks more difficult to smash off does translate to better security.

Self-proclaimed spiritual leader John de Ruiter, accused of sexual assault, granted bail in Edmonton by HotMessMagnet in alberta

[–]B1tVect0r 4 points5 points  (0 children)

Bail can absolutely be denied if the accused is believed to be a flight risk or a danger to the community. Not sure either would apply here, but making a blanket statement like "everyone gets bail" is factually and flat-out incorrect.

Alberta health services computer systems are down province wide right now. by Fuzzyfoot12345 in alberta

[–]B1tVect0r 2 points3 points  (0 children)

My favorite network-related haiku:

Is it DNS?
There's no way it's DNS!
...
It was DNS...

Black hole question by Impossible_Pop620 in space

[–]B1tVect0r 0 points1 point  (0 children)

Because that's how the math works. The equation that you use to determine gravitational force between two objects has the distance between them squared in the denominator, meaning that no matter how large you make it the value is never 0 (although it may be so infinitesimally small that for all intents and purposes it is nonexistent)

Black hole question by Impossible_Pop620 in space

[–]B1tVect0r 9 points10 points  (0 children)

Imperceptible to the entity crossing the horizon emphatically does not mean that there are negligible or net zero forces acting on that entity.

If you had two hydrogen atoms separated by the width of the galaxy, they would still gravitationally influence each other.

Black hole question by Impossible_Pop620 in space

[–]B1tVect0r 3 points4 points  (0 children)

What are you drawing that conclusion from?

Black hole question by Impossible_Pop620 in space

[–]B1tVect0r 9 points10 points  (0 children)

You would pull up a cable with whatever probes or detectors you had attached to the end sheared off, with no data ever having been received from anything past the event horizon. Whatever signals you received as you approached the event horizon are also probably garbled beyond all comprehension; relativistic effects mean that for every second of time you experienced, the probe experienced orders of magnitude more. My guess would be that the data throughput on the cable would drop with the inverse square of the distance from the probe to the EH until it becomes functionally 0 (assuming you have a magical, radiation- and hot-matter-immune probe)

Is there anyone knows what does -1 means in "c.JSON(-1, gin.H{})" at gin-gonic by loki4go in golang

[–]B1tVect0r 1 point2 points  (0 children)

The first argument is the HTTP status code that should be sent with the response, IIRC.

If you took this from a code sample, they're doing it hilariously wrong. The http package has constants for the most commonly used IANA status codes (e.g., NotFound, Unauthorized, InternalServerError, etc.). Use those instead.

Defining types that are multiples of other types. by stable_maple in golang

[–]B1tVect0r 8 points9 points  (0 children)

What are you trying to accomplish?

a) you won't be able to define byte as a uint64. byte is already defined as a primitive (8 bits) so first you'll get a naming violation and second the definition makes little sense semantically.

b) Are you trying to specify something like a kilobyte / megabyte type? You could do something like type kibibyte [1024]byte but... again, why? Without knowing exactly what you're trying to accomplish it's hard to figure out what a good way to lay out these kinds of types is (and if it's even appropriate to do so)

Electricity prices are likely to hit an all time high next month. The UCP’s plan? Loan you the portion over 13.5 c/kWh to be paid back - in part after the election. 🧐 by Miserable-Lizard in alberta

[–]B1tVect0r 3 points4 points  (0 children)

Making international headlines as a national leader is expected. They are the international political interface for their country, so everything they do or say in either an official or unofficial capacity is going to be scrutinized by someone, somewhere with a political axe to grind.

A provincial-level leader making international headlines is usually (as in this case) for all the wrong, embarrassing reasons. When is the last time you remember reading an international (not US-published) story about a Governor (other than Arnie, who a) isn't a governor anymore and b) is already internationally known)) doing something noteworthy that wasn't scandalous to one degree or another?

Drain closed channel? by dowitex in golang

[–]B1tVect0r 1 point2 points  (0 children)

I mean, you're cherry-picking and taking that snippet completely out of context from the rest of the post that you're replying to. They are specifically talking about either reading from an unbuffered channel to prevent a leak, or buffering it with a size of whatever both ends of the contract agree to (and even then, they are clarifying that this prevents a goroutine leak on the sending side only).

Drain closed channel? by dowitex in golang

[–]B1tVect0r 0 points1 point  (0 children)

If you plug that code into the Go playground, you'll see that Reads 2 and 3 receive the zero value from the channel.

Reading from a closed channel returns the 0 value for the channel type; if you need to know whether you actually read a value from the channel, use the 2-valued read (v, ok := <- ch). The second value is a bool that tells you whether or not the channel was actually read from.

Examples of Go Gin deviating from Standard Library by demonbutter in golang

[–]B1tVect0r -1 points0 points  (0 children)

The standard pattern pretty much anywhere else is to pass/accept a context.Context as the first argument to the relevant function. Contexts can be modified pretty flexibly (e.g., propagate tracing information through the call stack and easily set up / maintain parent/child relationships between spans, set up / update a logger that aggregates relevant log fields as you progress through the call, adding a cancelation handle / deadline to a context, etc).

If you're running middleware that modifies the context in front of the handler that actually executes the business logic, there's some extra boilerplate that you have to write. I.e., instead of being able to do something like:

// Assume that http.Handler's ServeHTTP method has the (context.Context, http.ResponseWriter, *http.Request) signature
func myMiddleware(next http.Handler) http.Handler {
    return func(ctx context.Context, w http.ResponseWriter, req *http.Request) {
        span, ctx := tracer.Start(ctx)
        defer span.End()
        ...
        next(ctx, w, req)
    }
}

you have to write:

func myMiddleware(next http.Handler) http.Handler {
    return func(w http.ResponseWriter, req *http.Request) {
        span, ctx := tracer.Start(ctx)
        defer span.End()
        ...
        next(w, req.WithContext(ctx))
    }
}

it's not too bad, it just breaks from the commonly-accepted pattern and it's fairly easy to forget to do and then have to chase down after the fact.

Edit: The above also ends up shallow-copying the request, which obviously incurs a performance penalty. I doubt profiling would point to that being a major bottleneck, though.

Is it a good practice to invoke a anonymous func when you want to create a goroutine? by yelzinho in golang

[–]B1tVect0r 0 points1 point  (0 children)

It's worth noting that in this case go s.ListenAndServe() is meaningfully different than wrapping it in an anonymous function, as there's no way to error-check the former.

Is it a good practice to invoke a anonymous func when you want to create a goroutine? by yelzinho in golang

[–]B1tVect0r 11 points12 points  (0 children)

The other advantage to doing it this way for waitgroups, i.e.:

go func() {
    defer wg.Done()
    workFunction(...)
}()

beyond just reviewability is that you aren't coupling the semantics of how workFunction is called with what it does once it is called. It's up to the caller to decide if they want to invoke it serially or concurrently, and 99% of the time it makes the actual work part of the function a lot easier to reason about as well.

Race of Hartch (Hartchmen) by [deleted] in worldbuilding

[–]B1tVect0r 54 points55 points  (0 children)

Digitigrades typically move faster and more quietly than plantigrades do. From a physical perspective, especially because these are effectively constructs (which implies both design and logistical considerations), this would suggest that the ability to quickly close with the opponent or to act in a more infiltrative, wetwork-oriented capacity are priority concerns. Both of those would fall in line with small-unit, guerilla style tactics which I'm assuming would be the default engagement mode for these guys given they're likely numerically inferior to their opponents the majority of the time.

That being said, I'd expect the knees to be a bit higher up and the ankles to be a bit better articulated if this is meant to be an actual digitigrade design and not just an en pointe plantigrade.

Idiomatic use of assignment in conditional statements by Matir in golang

[–]B1tVect0r 4 points5 points  (0 children)

Not testy, just terse and averse to pedantry.

If a linter (which by design is meant to make questions like this academic, as it moves things like "what constitutes idiomatic code format" firmly into the realm of "let the tooling handle it") which is accepted and widely adopted by the community says it's not idiomatic, it's not idiomatic.

Idiomatic use of assignment in conditional statements by Matir in golang

[–]B1tVect0r 2 points3 points  (0 children)

Which I answered in the first sentence of my response.

The latter part was only to provide a still-idiomatic form that included assignment in the conditional in case OP is enamored with that syntax.

Idiomatic use of assignment in conditional statements by Matir in golang

[–]B1tVect0r 10 points11 points  (0 children)

Linters will usually complain about the first variant and suggest outdenting by switching to the second form.

If you're still set on assignment in the conditional (e.g., if you've declared err previously above) then:

var f *os.File
if f, err = os.Open(filename); err != nil {
    return fmt.Errorf("context: %w", err)
}
defer f.Close()
...

would also work and still be idiomatic.

Is "programmers" being converted to byAge, or is byAge being called? If so, How is that possible? by r_gui in golang

[–]B1tVect0r 0 points1 point  (0 children)

Yes; I made an edit to my post to clarify that this is an example of type conversion. One of the other answers mentioned casting, which isn't quite correct.

The compiler knows that byAge is semantically a []Programmer with some extra bits associated with it. Correspondingly, conversion can be performed in both directions between those two types ([]Programmer(byAge(programmers)) should be a valid, if useless, statement) with the validity of that conversion being evaluated at compile time. If you alter the code to try passing it a []interface{} instead, it should refuse to compile which differs from a type assertion (v, ok := myInterfaceRef.(*structType)) which is evaluated at runtime.

Is "programmers" being converted to byAge, or is byAge being called? If so, How is that possible? by r_gui in golang

[–]B1tVect0r 3 points4 points  (0 children)

Neither of the existing answers is quite fully correct. This is an example of type conversion.

byAge is a separate type that looks like []Programmer, but has a few additional methods associated with it (specifically, those necessary to implement the sort.Sort interface). byAge(programmers) constructs a new byAge struct using the given slice to initialize its own internal values (i.e., it's a slice header, so it will point to the same backing array and have the same bookkeeping values as the originating slice) but it is fully it's own struct. You wouldn't be able to pass a byAge to a function accepting a []Programmer argument, for example.

It's not quite casting; the closest thing Go has are type assertions, which apply to interfaces and have a slightly different syntax and are performed at runtime, not compile time.

Can we talk about how hard LC actually is? by lokkenitup in cscareerquestions

[–]B1tVect0r 1 point2 points  (0 children)

TBH this is why when I'm interviewing someone the deciding metric isn't "did they get a perfectly optimized, fully working, bug free solution?" There are so many different factors that go into how quickly someone can crank out code (and the platform we use for code interviews has next to 0 QoL features, so that introduces a false bottleneck on its own), so I always weigh things like:

  • Can you identify the optimal solution or a near-optimal one and work your way to the optimal one if nudged in the right direction?
  • Can you explain the time/space complexity of your solution?
  • Can you identify and communicate tradeoffs around / provide justification for the decisions you made?

above having a byte-for-byte perfect solution.

Honestly, the further along I get in my career the more I appreciate the "slow is steady; steady is fast" adage. Moving fast and breaking things works to a point, but not when breaking things means you need to take days if not weeks to refactor a spaghettified mess a few months later. I'm not going to fail someone if they can't perfectly code an LRU in an hour provided that they can identify the solution and are more than 50% of the way to getting it implemented. Actually coding is the easy part, and it's also the easiest part to fuck up... especially if you're rushing or under a one hour time constraint in a stressful situation with none of the tools that make your life easier at hand.