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

  • rushaction@programming.dev
    link
    fedilink
    arrow-up
    75
    ·
    edit-2
    6 months ago

    I’m going to try to help explain this, but i’ll be honest it feels like you’re coming from a place of frustration. I’m sorry about that, take a break :)

    (I’m not a language expert, but here goes)

    var test int < bruh what? :=

    These are the two forms of variable declaration and the second one is a declaration and initialization short hand. I most commonly use :=. For instance:

    foo := 1 // it's an int!
    var bar uint16 // variable will be assigned the zero value for unit16 which is unsurprisingly, 0.
    

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

    This has no return type because it returns no values. It does not require passing u. It’s a method on the User type, specifically u User is a method receiver. You might think of this akin to self or this variable in other languages. By convention it is a singke character of the type’s name.

    If that function returned a value it might look like:

    func(u User) hi() string {
        return "hi!"
    }
    

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

    This is confusing because of how it’s written. But the intent is to have a map (aka dictionary or hashmap) with string keys and int values. In your example it’s initializd to have no entries, the {}. Let me rewrite this a different way:

    ages := map[string]int{
        "Alice": 38,
        "Bob": 37,
    }
    

    Hope this helps. In all honesty, Go’s language is very simple and actually rather clear. There’s definitely some funny bits, but these aren’t it. Take a break, come back to it later. It’s hard to learn if you are frustrated.

    I also recommend doing the Tour of Go here. My engineers who found Go intimidating found it very accessible and helped them get through the learning code (as there is with any language).

    Good luck (I’m on mobile and didn’t check my syntax, hopefully my code works 😎)

  • Soviet Pigeon@lemmygrad.ml
    link
    fedilink
    arrow-up
    16
    arrow-down
    1
    ·
    edit-2
    6 months ago

    but Im seeing syntax that Ive never seen in my life

    Which languages do you know? What is your background?

    What is wrong with “var test int”? There is no need for a return type, if the function returns nothing. Thats the language design and I think it is easy to remember.

    func(u User) hi ()

    u is something like self in Python and hi() is a method of User.

    Please explain why do you think something is too messy, also with which languages you have already worked.

  • dudeami0@lemmy.dudeami.win
    link
    fedilink
    arrow-up
    12
    arrow-down
    1
    ·
    edit-2
    6 months ago

    Yea this is just syntax, every language does it a little different, most popular languages seem to derive off of C in some capacity. Some do it more different than others, and some are unholy conglomerations of unrelated languages that somehow works. Instead of saying why is this different, just ask how does this work. It’s made my life a lot simpler.

    var test int is just int test in another language.

    func (u User) hi () { ... } is just class User { void hi() { ... } } in another language (you can guess which language I’m referencing I bet).

    map := map[string]int {} is just Map<String, Integer> map = new HashMap<>() in another (yes it’s java).

    Also RTFM, this is all explained, just different!

    Edit: I also know this is a very reductive view of things and there are larger differences, I was mostly approaching this from a newer developers understanding of things and just “getting it to work”.

  • TootSweet@lemmy.world
    link
    fedilink
    English
    arrow-up
    10
    ·
    edit-2
    6 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?

  • 0x00@programming.dev
    link
    fedilink
    arrow-up
    7
    ·
    6 months ago

    My least favorite part of Go, by far, is the capitalization as struct member visibility thing. That and the not super great json encoding annotations.

    Here’s a sample:

    type Change struct {
    	Path             string `json:"path"`
    	Category         string `json:"category"` // change, append, create, delete
    	Position         int64  `json:"position"`
    	Size             int64  `json:"size"`
    	OriginalChecksum string `json:"original_checksum"`
    	UpdatedChecksum  string `json:"updated_checksum"`
    	UnixTimestamp    int64  `json:"unix_timestamp"`
    	Data             []byte `json:"data"`
    	MatchedRules     []Rule `json:"matched_rules"`
    }
    

    I would take explicit public declarators any day

  • hector@sh.itjust.works
    link
    fedilink
    arrow-up
    7
    ·
    6 months ago

    Wow it shows how much it boils down to préférence at the end of the day.

    I’m a Go fanboy, I cannot cite an aspect of the language I don’t like, find clunky…

    Wow. I love syntax, the tooling, the speed, the errors, the testing framework.

  • thingsiplay@beehaw.org
    link
    fedilink
    arrow-up
    6
    arrow-down
    2
    ·
    6 months ago

    The := operator is called walrus operator and is inspired by Python I think. It’s declaring a variable and assigning it in one go. map[string] int is defining a map (associative array or also known as dictionary in Python), with string as key type and int as value type. And the following {} is the body of the associative array, meaning empty content.

    I only played a bit with Go and did basic tutorials. I might go back to it at some point, but Zig is much more appealing to me. Go is too simple in the language to me, but on the other side, this is exactly whats appealing.

    • Atz@techhub.social
      link
      fedilink
      arrow-up
      7
      ·
      6 months ago

      @thingsiplay @urska
      ‘:=’ goes back to Pascal and maybe further. It also appears in PL/SQL. When I was learning to code my teacher told me to pronounce it as “becomes” since “equals” was for comparison.

      Took me a while to get used to the C style ‘==’.

    • BatmanAoD@programming.dev
      link
      fedilink
      arrow-up
      3
      ·
      6 months ago

      I was curious about the Python connection because multiple comments mentioned it, but I’ve worked on multiple Python projects over the past dozen-ish years and never seen that operator.

      Turns out it was introduced in 3.8, released in 2019, so it was much too late to inspire Go, and most of the projects I’ve worked on were written to target an earlier Python version. It also has a substantially different meaning than in Go.

      I don’t know if there’s an “official” rationale for the Go syntax, but := is a fairly common (but not ubiquitous) math notation meaning “define the thing on the left to be equal to the expression on the right”, i.e. to distinguish it from the other use of =, i.e. “the expression on the left must be equal to the expression on the right.” Go’s usage matches this mathematical meaning of introducing a new variable definition pretty well.

      • thingsiplay@beehaw.org
        link
        fedilink
        arrow-up
        1
        ·
        edit-2
        6 months ago

        Turns out it was introduced in 3.8, released in 2019, so it was much too late to inspire Go

        You are probably right about that. But don’t forget that the operator didn’t made it day one, there was lot of discussion before and probably testing it in the beta releases before. But given how old Golang at that point is, you are right about my take on inspiration. This operator wasn’t a new invention in Python.

        It also has a substantially different meaning than in Go.

        I don’t know if there’s an “official” rationale for the Go syntax, but := is a fairly common (but not ubiquitous) math notation meaning “define the thing on the left to be equal to the expression on the right”, i.e. to distinguish it from the other use of =, i.e. “the expression on the left must be equal to the expression on the right.”

        Does it though? In both cases, Go and Python, the operator will assign a variable a value and also use it as an expression. That is useful in cases like for loops or other cases where you want immediately use the variable content as an expression. This cannot be done with the regular assignment operator a = 69, which itself is not an expression. So in practical terms, its the same in usability for Go and Python. So its doing the same for both languages and has the same differences to the assignment operator. (Edit: Read the reply, I learned something myself. That’s why its important that you don’t blindly teach people like I did.)

        • BatmanAoD@programming.dev
          link
          fedilink
          arrow-up
          3
          ·
          6 months ago

          In both cases, Go and Python, the operator will assign a variable a value and also use it as an expression.

          That is absolutely not true. foo := <expr> is a statement in Go, full stop. Just try something trivial like assigning to the output of :=: https://go.dev/play/p/nPINGc7LO8B

          It’s true that if and for let you use := but don’t let you use var, but you still can’t use the result of the assignment directly. So for instance you need if foo := <expr>; foo { ... } rather than just if foo := <expr> { ... }.

          • thingsiplay@beehaw.org
            link
            fedilink
            arrow-up
            3
            ·
            6 months ago

            Ok I see, I stand corrected then. Its a misconception I had without actually going through all of this, so my bad (will edit my replies to mark them). At least in Python we can do this print(foo := (bar := 3)) but not on its own as foo := 3 .

    • Vivendi@lemmy.zip
      link
      fedilink
      arrow-up
      3
      ·
      6 months ago

      It goes back to mathematics pseudo code which was then used to sketch the ALGOL symbols way back in the days and which then gave birth to everything you know of programming today

      That shit’s quite ancient

      • thingsiplay@beehaw.org
        link
        fedilink
        arrow-up
        1
        arrow-down
        1
        ·
        edit-2
        6 months ago

        But that mathematical pseudo code has nothing in common with the walrus operator := in Python and Go. They are just the same symbols, but with a totally different meaning and use case. Its an operator designed specifically for programming languages, because that is not applicable to mathematics at all. In mathematics you don’t have an assignment operator a = 69 that cannot be used as part of an expression. Therefore you don’t need a dedicated := that yields an expression that can be used as part of an expression and create a variable if its not already. (Edit: I’m so sick of my stupidness.)

  • Solemarc@lemmy.world
    link
    fedilink
    arrow-up
    4
    ·
    6 months ago

    To do quick and simple explanations:

    var test int = 0
    

    assign an int, var = let in rust land

    := 
    

    This is basically an inferred assignment e.g.

    a := "hello world"
    

    The compiler will know this is a string without me explicitly saying

    func (u User) hi() {}
    

    To return to rust land this is a function that implements User. In OOP land we would say that this function belongs to the user class. In Go, just like in rust we don’t say if a function returns void so this function is for User objects and doesn’t return anything:

    func (u User) hi(s string) string {}
    

    If it took in a string and returned a string it would look like this.

    map[string] int {}
    

    I will give you that this syntax is a bit odd but this is just a hashmap/dictionary where the key is a string and the value is an int

  • sping@lemmy.sdf.org
    link
    fedilink
    English
    arrow-up
    6
    arrow-down
    14
    ·
    6 months ago

    The more time I spend on Lemmy the more depressed I am about its potential.

    Stupid, wrong-headed comments get solid upvotes if they also hint at some popular sentiment. I even see comments that are literally unreadable nonsense get solidly upvoted, either by bots or by people who just like the vibe they feel from scanning it and don’t care that it’s gobbledygook. Some content makes me wonder if half of Lemmy is just LLMs barfing back and forth at each other.

    Then this post is heavily upvoted, even though it’s nothing more than “the syntax isn’t the same as the other language(s) I have seen, waaaaa!”. Is it just people like to see Go criticized? Because there are actual real issues that could be discussed.

    • UndercoverUlrikHD@programming.dev
      link
      fedilink
      arrow-up
      10
      arrow-down
      1
      ·
      6 months ago

      I’m curious what’s triggering you, as of writing this comment, the (5) comments I see are all reasonable explanations that tries to help OP understand the language.

      Upvotes does not necessarily mean people agree with OP’s stance.

      • sping@lemmy.sdf.org
        link
        fedilink
        English
        arrow-up
        4
        arrow-down
        4
        ·
        6 months ago

        I’m not triggered by any of this. I’m not sure why my thinking the question is inane would count as “being triggered”.

        Upvotes does not necessarily mean people agree with OP’s stance.

        It should mean they think it’s a useful/interesting question and I think it very much is not. It’s just someone whining that it doesn’t look like something they’re used to and a bunch of very patient people generously leading them through the very basics of the language that’s well covered in many introductory tutorials - as such it makes it all a waste of time and worthy of being buried.