Why is Go syntax so messy - eviltoast

I understand Rust being type safe, but Im seeing syntax that Ive never seen in my life in Go which looks too messy

var test int < bruh what?

:=

func(u User) hi () { … } Where is the return type and why calling this fct doesnt require passing the u parameter but rather u.hi().

map := map[string] int {} < wtf

  • TootSweet@lemmy.world
    link
    fedilink
    English
    arrow-up
    10
    ·
    edit-2
    5 months ago

    map := map[string] int {}

    Not sure where you got your examples, but the spacing is pretty wonky on some (which can’t possibly help with confusion) and this one in particular causes a compile-time error. (It’s kindof trying to declare a variable named “map”, but “map” is a reserved word in Go.)

    var test int < bruh what?

    This article gives the reasoning for the type-after-variable-name declaration syntax.

    :=

    Lots of languages have a colon-equals construction. Python for one. It’s not terribly consistent what it means between languages. But in Go it declares and assigns one or more variables in one statement and tells Go to figure out the types of the variables for you so you don’t have to explicitly tell it the types to use.

    func(u User) hi () { … }

    That function (“method”, really, though in Go it’s more idiomatic to call it a “receiver func”) has no return values, so no return type. (Similar to declaring a function/method " void in other languages.)

    The first pair of parens says to make this “function” a “method” of the “User” type (which must be declared in the same package for such a function declaration to work.) The whole “when I call it like u.hi(), don’t make me pass u as a parameter as well as putting u before the period” thing also has precedent in plenty of other languages. Python, again, is a good example.

    Oh, and the second set of parens are where the function’s (non-receiver) parameters go. Your example just doesn’t take any. A function like func (u User) say(msg string) { ... }, for instance, could be called with u.say("Hey."). func (u User) ask(question string) string { ... } has a return type of string. So you could do var ans string = u.ask("Wuzzup?") or ans := u.ask("Wuzzup?").

    I can’t say I was ever too taken aback with Go’s syntax. Just out of curiosity, what languages do you have experience with?