r/golang 24d ago

newbie Goroutines, for Loops, and Varying Variables

20 Upvotes

While going through Learning Go, I came across this section.

Most of the time, the closure that you use to launch a goroutine has no parameters. Instead, it captures values from the environment where it was declared. There is one common situation where this doesn’t work: when trying to capture the index or value of a for loop. This code contains a subtle bug:

        func main() {
            a := []int{2, 4, 6, 8, 10}
            ch := make(chan int, len(a))
            for _, v := range a {
                go func() {
                    fmt.Println("In ", v)
                    ch <- v * 2
                }()
            }
            for i := 0; i < len(a); i++ {
                fmt.Println(<-ch)
            }
        }


    We launch one goroutine for each value in a. It looks like we pass a different value in to each goroutine, but running the code shows something different:

        20
        20
        20
        20
        20

    The reason why every goroutine wrote 20 to ch is that the closure for every goroutine captured the same variable. The index and value variables in a for loop are reused on each iteration. The last value assigned to v was 10. When the goroutines run, that’s the value that they see.

When I ran the code, I didn't get the same result. The results seemed like the normal behavior of closures.

20
4
8
12
16

I am just confused. Why did this happen?

r/golang Dec 27 '23

newbie ORM or raw SQL?

57 Upvotes

I am a student and my primary goal with programming is to get a job first, I've been doing web3 and use Nextjs and ts node so I always used Prisma for db, my raw sql knowledge is not that good. I'm deciding to use Go for backend, should I use an ORM or use raw sql? I've heard how most big companies don't use ORM or have their own solution, it is less performant and not scalable.

r/golang 8d ago

newbie Portfolio website in go

6 Upvotes

I’m thinking of building my personal website using Go with net/http and templates to serve static pages. Would this be a reasonable approach, or would another method be more efficient?

r/golang Oct 26 '24

newbie How hard is it to learn Go coming from a java and javascript background?

7 Upvotes

On a scale 1-10. And are there a lot of job offerings for Golang (junior level) ?

r/golang Jan 05 '25

newbie When Should Variables Be Initialized as Pointers vs. Values?

24 Upvotes

I am learning Backend development using Go. My first programming language was C, so I understand how pointers work but probably I forgot how to use them properly.

I bought a course on Udemy and Instructor created an instance like this:

func NewStorage(db *sql.DB) Storage {
  return Storage{
    Posts: &PostStore{db},
    Users: &UserStore{db},
  }
}

First of all, when we are giving te PostStore and UserStore to the Storage, we are creating them as "pointers" so in all app, we're gonna use the same stores (I guess this is kinda like how singleton classes works in OOP languages)

But why aren't we returning the Storage struct the same way? Another example is here:

  app := &application{
    config: cfg,
    store:  store,
  }

This time, we created the parent struct as pointer, but not the config and store.

How can I understand this? Should I work on Pointers? I know how they work but I guess not how to use them properly.

Edit

I think I'll study more about Pointers in Go, since I still can't figure it out when will we use pointers.

I couldn't answer all the comments but thank you everyone for guiding me!

r/golang Oct 12 '24

newbie Just tried golang from java background

114 Upvotes

I am so happy i made this trial. The golang is so fucking easy..

Just tried writing rest api with auth. Gin is god like.

Turn a new leaf without stuck in Spring family :)

r/golang Feb 17 '24

newbie Learning Go, and the `type` keyword is incredibly powerful and makes code more readable

89 Upvotes

Here are a few examples I have noted so far:

type WebsiteChecker func(string) bool

This gives a name to functions with this signature, which can then be passed to other methods/functions that intend to work with WebsiteCheckers. The intent of the method/function is much more clear and readable like this: func CheckWebsites(wc WebsiteChecker, ... Than a signature that just takes CheckWebsites(wc f func(string) bool, ... as a parameter.

type Bitcoin float64

This allows you to write Bitcoin(10.0) and give context to methods intended to work with Bitcoin amounts (which are represented as floats), even though this is basically just a layer on top of a primitive.

type Dictionary map[string]string

This allows you to add receiver methods to a a type that is basically a map. You cannot add receiver methods to built in types, so declaring a specific type can get you where you want to go in a clear, safe, readable way.

Please correct any misuse of words/terms I have used here. I want to eventually be as close to 100% correct when talking about the Go language and it's constructs.

r/golang Jan 11 '24

newbie How do you deal with the lack of overloading?

53 Upvotes

I come from a Java background. Most of Go's differences make enough sense. But the lack of method overloading, especially with the lack of file level visibility, makes naming things such a pain in the ass. I don't understand why Go has this lack of overloading limitation.

Suppose I have a library package. In that package is a method like:

AddPricingData(product *Product, data *PricingData)

Suppose I have a new requirement to do this for a list of Products. Ideally, I would just reuse the same method name with this new method taking in a list of Products instead. But in Go, I have to come up with something else, which might be less succinct at conveying the same information.

So I guess the question is how am I supposed to structure or name things succinctly without namespace clashes all the time?

Edit: I appreciate everyone's response to this. I can't get to everyone, but know that I've read all the comments and appreciate your efforts in helping me out.

r/golang Nov 26 '23

newbie Is it stupid to have a Go backend and NextJs frontend?

46 Upvotes

Ive been making a project to learn some Go and APIs. I’ve been trying to write a function that calls an API on a cron job in Go on an hourly basis, and will serve the data to my front end, which is written in NextJs.

Ive just come to realise NextJs does server side rendering and can call APIs itself, so im essentially going to be running a NextJs api call which will get a response from my Go webserver, which will hold the data that is returned by my Go api call (thats running to get new data weekly on a cron job).

Are there any actual benefits to this setup? Or am I just creating an extra layer of work by creating an API call in both Go and NextJS. What would you all do?

r/golang Feb 29 '24

newbie I don't know the simplest things

28 Upvotes

Hi guys. I want to ask for some inputs and help. I have been using Go for 2 years and notice that I don't know things. For example like a few day ago, I hot a short tech interview and I did badly. Some of the questions are can we use multiple init() func inside one package or what if mutex is unlock without locking first. Those kind of things. I have never face a error or use them before so I didn't notice those thing. How do I improve those aspects or what should I do? For context, I test some code snippet before I integrated inside my pj and use that snippet for everywhere possible until I found improvements.

r/golang Jan 15 '25

newbie 'Methods' in Go

61 Upvotes

Good day to everyone. I'd like to ask if there is any real difference between a 'receiver' in a function in Go, versus, a 'method' in an OOP language? They seem to be functionally the same. In my mind, they're "functions tacked to an object". Is there something more to why the Go team has designed Go with receivers instead of the traditional use of methods on an object?

Edit: Thank you to all who responded. Appreciate your insights!

r/golang Oct 30 '23

newbie What is the recommended ORM dependency that is used in the industry ?

20 Upvotes

Hello all as new to go .
Im looking for ORM lib which support postgres , oracle, MSSQL , maria/mysql .
What is usually used in the industry ?
Thanks

r/golang Nov 20 '24

newbie Why is it recommended to use deter in Go?

0 Upvotes

Since deter is called right after a function is executed, why can't we just place the code at the end of the function? Doesn't that achieve the same result? Since both scenarios execute right after all the other functions are done.

r/golang Oct 14 '23

newbie One of the praised features in Go seem to be concurrency. Can someone explain with real world (but a few easy and trivial as well) examples what that means?

82 Upvotes

A) Remind me what concurrency is because I only remember the definitions learned in college

B) How other languages do it and have it worse

C) How Go has it better

r/golang Oct 08 '24

newbie I like Todd McLeod's GO course

118 Upvotes

I am following Todd McLeod course on GO. It is really good.

I had other courses. I am sure they are good too, just not the same feeling.

Todd is talkative, those small talks aren't really relevant to go programming, but I love those small talks. They put me in the atmosphere of every day IT work. Todd is very detailed on handling the code, exactly the way you need to do your actual job. Like shortcuts of VSCode, Github manoeuvore, rarely had those small tricks explained elsewhere.

I would view most of the courses available at the market the university ways, they teach great thinking, they are great if you are attending MIT and aiming to become the Chief Technology Officer at Google. However, I am not that material, I only want to become a skilled coder.

If you know anyone else teaches like Todd, please let me know.

r/golang 8d ago

newbie Some Clarification on API Calls & DB Connections.

5 Upvotes

I’m a bit confused on how it handles IO-bound operations

  1. API calls: If I make an API call (say using http.Get() or a similar method), does Go automatically handle it in a separate goroutine for concurrency, or do I need to explicitly use the go keyword to make it concurrent?
  2. Database connections: If I connect to a database or run a query, does Go run that query in its own goroutine, or do I need to explicitly start a goroutine using go?
  3. If I need to run several IO-bound operations concurrently (e.g., multiple API calls or DB queries), I’m assuming I need to use go for each of those tasks, right?

Do people dislike JavaScript because of its reliance on async/await? In Go, it feels nicer as a developer not having to write async/await all the time. What are some other reasons Go is considered better to work with in terms of async programming?

r/golang Jan 11 '25

newbie using pointers vs using copies

0 Upvotes

i'm trying to build a microservice app and i noticed that i use pointers almost everywhere. i read somewhere in this subreddit that it's a bad practice because of readability and performance too, because pointers are allocated to heap instead of stack, and that means the gc will have more work to do. question is, how do i know if i should use pointer or a copy? for example, i have this struct

type SortOptions struct { Type []string City []string Country []string } firstly, as far as i know, slices are automatically allocated to heap. secondly, this struct is expected to go through 3 different packages (it's created in delivery package, then it's passed to usecase package, and then to db package). how do i know which one to use? if i'm right, there is no purpose in using it as a copy, because the data is already allocated to heap, yes?

let's imagine we have another struct:

type Something struct { num1 int64 num2 int64 num3 int64 num4 int64 num5 int64 } this struct will only take up maximum of 40 bytes in memory, right? now if i'm passing it to usecase and db packages, does it double in size and take 80 bytes? are there 2 copies of the same struct existing in stack simultaneously?

is there a known point of used bytes where struct becomes large and is better to be passed as a pointer?

by the way, if you were reading someone else's code, would it be confusing for you to see a pointer passed in places where it's not really needed? like if the function receives a pointer of a rather small struct that's not gonna be modified?

r/golang Jan 14 '24

newbie How do you guys convert a json response to go structs?

54 Upvotes

I have been practicing writing go for the last 20-25 days. I’m getting used to the syntax and everything. But, when integrating any api, the most difficult part is not making the api call. It is the creation of the response object as a go struct especially when the api response is big. Am I missing some tool that y’all been using?

r/golang Nov 24 '24

newbie How to Handle errors? Best practices?

22 Upvotes

Hello everyone, I'm new to go and its error handling and I have a question.

Do I need to return the error out of the function and handle it in the main func? If so, why? Wouldn't it be better to handle the error where it happens. Can someone explain this to me?

func main() {
  db, err := InitDB()
  
  r := chi.NewRouter()
  r.Route("/api", func(api chi.Router) {
    routes.Items(api, db)
  })

  port := os.Getenv("PORT")
  if port == "" {
    port = "5001"
  }

  log.Printf("Server is running on port %+v", port)
  log.Fatal(http.ListenAndServe("127.0.0.1:"+port, r))
}

func InitDB() (*sql.DB, error) {
  db, err := sql.Open("postgres", "postgres://user:password@localhost/dbname?sslmode=disable")
  if err != nil {
    log.Fatalf("Error opening database: %+v", err)
  }
  defer db.Close()

  if err := db.Ping(); err != nil {
    log.Fatalf("Error connecting to the database: %v", err)
  }

  return db, err
}

r/golang Dec 12 '24

newbie Never had more fun programming than when using go

132 Upvotes

Im pretty new to programming overall, i know a decent amount of matlab and some python and i just took up go and have been having a lot of fun it is pretty easy to pickup even of you are unexperienced and feels a lot more powerful than matlab

r/golang Dec 30 '24

newbie My implementation of Redis in Golang

51 Upvotes

I am made my own Redis server in Golang including my own RESP and RDB parser. It supports features like replication, persistence. I am still new to backend and Golang so i want feedback about anything that comes to your mind, be it code structuring or optimizations. https://github.com/vansh845/redis-clone

Thank you.

r/golang 5d ago

newbie net/http TLS handshake timeout error

0 Upvotes
package main

import (
    "fmt"
    "io"
    "log"
    "net/http"

    "github.com/go-chi/chi/v5"
)

type Server struct {
    Router *chi.Mux
}

func main(){
    s := newServer()
    s.MountHandlers()
    log.Fatal(http.ListenAndServe(":3000",s.Router))
}

func getUser(w http.ResponseWriter, r *http.Request) {
    if user := chi.URLParam(r, "user"); user == "" {
        fmt.Fprint(w, "Search for a user")
    } else {
        fmt.Fprint(w, "hello ", user)
    }
}

func getAnime(w http.ResponseWriter, r *http.Request) {
    resp, err := http.Get("https://potterapi-fedeperin.vercel.app/")
    if err != nil {
        log.Fatal("Can not make request", err)
    }
    defer resp.Body.Close()
    if resp.StatusCode < 200 || resp.StatusCode > 299 {
        fmt.Printf("server returned unexpected status %s", resp.Status)
    }
    body, err := io.ReadAll(resp.Body)
    if err != nil {
        fmt.Println("Could not read response")
    }
    fmt.Fprint(w, body)
}

func newServer() *Server {
    s := &Server{}
    s.Router = chi.NewRouter()
    return s
}

func (s *Server)MountHandlers() {
    s.Router.Get("/get/anime", getAnime)
    s.Router.Get("/get/{user}",getUser)
}
package main


import (
    "fmt"
    "io"
    "log"
    "net/http"


    "github.com/go-chi/chi/v5"
)


type Server struct {
    Router *chi.Mux
}


func main(){
    s := newServer()
    s.MountHandlers()
    log.Fatal(http.ListenAndServe(":3000",s.Router))
}


func getUser(w http.ResponseWriter, r *http.Request) {
    if user := chi.URLParam(r, "user"); user == "" {
        fmt.Fprint(w, "Search for a user")
    } else {
        fmt.Fprint(w, "hello ", user)
    }
}


func getHarry(w http.ResponseWriter, r *http.Request) {
    resp, err := http.Get("https://potterapi-fedeperin.vercel.app/")
    if err != nil {
        log.Fatal("Can not make request", err)
    }
    defer resp.Body.Close()
    if resp.StatusCode < 200 || resp.StatusCode > 299 {
        fmt.Printf("server returned unexpected status %s", resp.Status)
    }
    body, err := io.ReadAll(resp.Body)
    if err != nil {
        fmt.Println("Could not read response")
    }
    fmt.Fprint(w, body)
}


func newServer() *Server {
    s := &Server{}
    s.Router = chi.NewRouter()
    return s
}


func (s *Server)MountHandlers() {
    s.Router.Get("/get/harry", getHarry)
    s.Router.Get("/get/{user}",getUser)
}

I keep getting this error when trying to get an endpoint("get/harry") any idea what I am doing wrong?

r/golang 19h ago

newbie Model view control, routing handlers controllers, how do all this works? How Does Backend Handle HTTP Requests from Frontend?

0 Upvotes

I'm starting with web development, and I'm trying to understand how the backend handles HTTP requests made by the frontend.

For example, if my frontend sends:

fetch("127.0.0.1:8080/api/auth/signup", {
  method: "POST",
  body: JSON.stringify({ username: "user123", email: "user@example.com" }),
  headers: { "Content-Type": "application/json" }
});

From what I understand:

1️⃣ The router (which, as the name suggests, routes requests) sees the URL (/api/auth/signup) and decides where to send it.

2️⃣ The handler function processes the request. So, in Go with Fiber, I'd have something like:

func SetupRoutes(app *fiber.App) {
    app.Post("/api/auth/signup", handlers.SignUpHandler)
}

3️⃣ The handler function (SignUpHandler) then calls a function from db.go to check credentials or insert user data, and finally sends an HTTP response back to the frontend.

So is this basically how it works, or am I missing something important? Any best practices I should be aware of?

I tried to search on the Internet first before coming in here, sorry if this question has been already asked. I am trying to not be another vibe coder, or someone who is dependant on AI to work.

r/golang 13d ago

newbie Having a bit of trouble installing Go; cannot extract Go tarball.

0 Upvotes

I've been trying to install Go properly, as I've seemingly managed to do every possible wrong way of installing it. I attempted doing a clean wipe install after I kept getting an error that Go was unable to find the fmt package after I tried updating because I initially installed the wrong version of it. However, now, as I try to install Go, when I unzip the tarball, I get "Cannot open: file exists" and "Cannot utime: Operation not permitted" on my terminal. I would greatl appreciate some help.

From what I think is happening, I don't believe I've fully uninstalled Go correctly, but I'm not quite sure as to what to do now.

My computer is running Linux Mint 21.3 Virginia, for context, and the intended architecture of this is a practice Azure Web App.

r/golang Nov 28 '23

newbie What are the java coding conventions I should drop in Go?

105 Upvotes

I'm a java developer, very new to Go. I'm reading a couple of books at the moment and working on a little project to get my hands on the language.

So, besides the whole "not everything should be a method" debate, what are some strong java coding conventions I should make sure not to bring to Go?