Earlier quoted context omitted.
Go doesn't protect you against race conditions, it merely offers some concurrency tools. There is nothing to declare ownership of objects in memory. So the compiler doesn't (can't) complain if you share memory and access it simultaneously. At best, there are runtime checks. Rust does offer compiler protection against that. Edit: "merely", relatively to Rust :) on an absolute scale, still way better than C for concurr…
As a total beginner (learning programming by myself since 2 or 3 years), i am always asking myself, how often "little" things like race conditions break something in production. Sure thing, some applications need to be safe-super-safe. But is it worth to switch over from go to rust as a beginner, since go is the unsafer language? I know, that there is no ultimate language. But i always asked myself i am missing a poi…
Rookie mistake (and a shoot-yourself-in-the-foot-at-2-am) mistake coming up:
package main
import ( "fmt" "sync" )
func main() { var wg sync.WaitGroup
for i := 0; i
go func() {
fmt.Printf("i= %d\n", i)
wg.Done()
}()
}
wg.Wait()
}https://play.golang.org/p/XDzFq_XK_1
And what about this code:
package main
import "fmt"
func main() {
var intArray []int for i := 0; i
intArray = append(intArray, i)
fmt.Printf("i= %d\n", i)
}
fmt.Println(intArray)
}https://play.golang.org/p/UuI4uESZ_f
If you don't care if intArray is in the proper order, you might do something like this:
package main
import ( "fmt" "sync" )
func main() { var wg sync.WaitGroup var intArray []int
for i := 0; i
go func(i int) {
intArray = append(intArray, i)
fmt.Printf("i= %d\n", i)
wg.Done()
}(i)
}
wg.Wait()
fmt.Println(intArray)
}What's wrong?
On my multi-core computer (though not on playground), len(intArray) could be as low as 500!
Why?
Because a = append isn't atomic.
Go, which is so pedantic about "stupid" mistakes (including something, changing your mind, and not "unincluding" it), didn't catch this. Not an error and no warning.
But the worst part is that when you loop until 10, it works. You can unit test it, integrate test it, and have it break at any point in time.