Go rand.Intn same number/value - random

Can anyone please tell me why the Go example here:
https://tour.golang.org/basics/1
always returns the same value for rand.Intn(10)?

2 reasons:
You have to initalize the global Source used by rand.Intn() and other functions of the rand package using rand.Seed(). For example:
rand.Seed(time.Now().UnixNano())
See possible duplicate of Difficulty with Go Rand package.
Quoting from package doc of rand:
Top-level functions, such as Float64 and Int, use a default shared Source that produces a deterministic sequence of values each time a program is run. Use the Seed function to initialize the default Source if different behavior is required for each run.
The Tour runs examples on the Go Playground which caches its output.
See details at Why does count++ (instead of count = count + 1) change the way the map is returned in Golang.

For the functions in the rand package to work you have to set a 'Seed' value. This has to be a good random value as decided by the user because - as per https://golang.org/pkg/math/rand/#Rand.Seed this is the value golang uses to set the system to a deterministic state first to then generate a number based on that value.
For the sample code to work, you can try
func main() {
rand.Seed(time.Now().UnixNano())
fmt.Println("My favorite number is ", rand.Intn(10))
}
time.Now().UnixNano can give an arbitrary(like) number as the value is in 'one thousand-millionth of a second'

As explained you have to initalize the global Source used by rand.Intn() and other functions of the rand package.
Besides using rand.Seed() option, you also can create the source using the methods rand.NewSource() and rand.New().
source := rand.NewSource(time.Now().UnixNano())
r := rand.New(source)
randomNumber := r.Intn(10)
fmt.Println("A random number: ", randomNumber)

Related

Why doesn't Go have a function to calculate the absolute value of integers?

In Go, why is there no function which directly calculates absolute value for integer datatypes? Currently all integer values have to be typecast to float64 and then passed to math.Abs(), which returns a float64, which again has to be typecast into an integer.
This code raises a ./prog.go:12:39: cannot use x (type int64) as type float64 in argument to math.Abs error because Go is a statically typed language, so it does not allow a different datatype:
package main
import (
"fmt"
"math"
)
func main() {
fmt.Println("Hello, playground")
var x int64 = -10
fmt.Println("Abolute value ", math.Abs(x))
}
From Go's FAQ,
The standard library's purpose is to support the runtime, connect to the operating system, and provide key functionality that many Go programs require, such as formatted I/O and networking. It also contains elements important for web programming, including cryptography and support for standards like HTTP, JSON, and XML.
There is no clear criterion that defines what is included because for a long time, this was the only Go library. There are criteria that define what gets added today, however.
New additions to the standard library are rare and the bar for inclusion is high. Code included in the standard library bears a large ongoing maintenance cost (often borne by those other than the original author), is subject to the Go 1 compatibility promise (blocking fixes to any flaws in the API), and is subject to the Go release schedule, preventing bug fixes from being available to users quickly.
Most new code should live outside of the standard library and be accessible via the go tool's go get command. Such code can have its own maintainers, release cycle, and compatibility guarantees. Users can find packages and read their documentation at godoc.org.
In response to how easy it is to create integer versions of the math package's float functions, Go team member Russ Cox once quipped,
Ceil, Floor, and Trunc are even easier!
A reasonable interpretation would be that since this function is trivial to write (if x < 0, x = -x), it does not meet the bar for inclusion. Compare with the float version:
func Abs(x float64) float64 {
return Float64frombits(Float64bits(x) &^ (1 << 63))
}
This being useful but also not obvious is a compelling reason to include it in the standard library.
Absolute value is just a special case of absolute difference [1], where the
second value is zero. Here is absolute value function for integers, as well as
absolute difference function for integers. Bonus is absolute difference
function for unsigned integers:
package math
func absInt(x int) int {
return absDiffInt(x, 0)
}
func absDiffInt(x, y int) int {
if x < y {
return y - x
}
return x - y
}
func absDiffUint(x, y uint) uint {
if x < y {
return y - x
}
return x - y
}
https://wikipedia.org/wiki/Absolute_difference
Though there is no standard function, you always can write it yourself or use third party solution. This package contains Abs functions for all builtin signed integer types. Usage (after go get):
import (
"fmt"
"github.com/adam-lavrik/go-imath/i64" // Functions for i64 type
)
...
x := int64(-2)
fmt.Println(i64.Abs(x)) // Output: 2
x = i64.Minimal // Minimal negative value of int64, has no positive pair
fmt.Println(i64.Absu(x)) // Output: 9223372036854775808 (result is converted to uint64)

How can I access DOM Element properties from Go WebAssembly?

I'm trying to extend the "Hello WebAssembly" example from https://github.com/golang/go/wiki/WebAssembly. As given, the example simply prints a message to the console. I wanted to add some code using syscall/js to replace the body element content.
The attempt below fails to build:
package main
import (
"fmt"
"syscall/js"
)
func main() {
fmt.Println("Hello, WebAssembly!") // original example
// I added
doc := js.Global().Get("document")
body := doc.Call("getElementById", "thebody")
body.innerHTML = "Dynamic Content"
}
When I try to build with $ env GOOS=js GOARCH=wasm go build -o main.wasm
I get :
./wasm.go:14:6: body.innerHTML undefined (type js.Value has no field or method innerHTML)
Not surprising when you think about it, but I don't see an example in the doc at https://godoc.org/syscall/js that explains how to get and set element properties.
To get the value of any property of some JavaScript object, use the Value.Get() method (you actually already used it when you accessed the document object by calling js.Global().Get("document")). Similarly, to set a value of a property, use Value.Set().
The name of the property whose value to get / set is simply a Go string value, "innerHTML" in your case. The value to be set may be many of Go values (e.g. string, integer numbers, floating point numbers, bool, slices, maps etc.), the js.ValueOf() function is used to obtain a js.Value() that will be set ultimately. In your case, you may simply use the Go string value "Dynamic Content".
doc := js.Global().Get("document")
body := doc.Call("getElementById", "thebody")
body.Set("innerHTML", "Dynamic Content")

Println changes capacity of a slice

Consider the following code
package main
import (
"fmt"
)
func main() {
x := []byte("a")
fmt.Println(x)
fmt.Println(cap(x) == cap([]byte("a"))) // prints false
y := []byte("a")
fmt.Println(cap(y) == cap([]byte("a"))) // prints true
}
https://play.golang.org/p/zv8KQekaxH8
Calling simple Println with a slice variable, changes its capacity. I suspect calling any function with variadic parameters of ...interface{} produces the same effect. Is there any sane explanation for such behavior?
The explanation is, like bradfitz point in github, if you don't use make to create a slice, the compiler will use the cap it believes convenient. Creating multiple slices in different versions, or even the same, can result on slices of different capacities.
In short, if you need a concrete capacity, use make([]byte, len, cap). Otherwise you can't trust on a fixed capacity.

Generalizing Concurrent Map Function with Empty Interface In GOlang

So I'm super new to Golang and seeing as the big buzz around the language seems to be concurrency I figured a good way to get my toes wet would be to write a generalized map function. In psudo code:
map(F funtion,A array){
return([F(k) for k in A])
}
And obviously I want the calculations for each F(k) occur concurrently. For organization I have a main file with my implementation and a supporting file Mr with my required definitions.
.
├── main.go
└── Mr
   └── Mr.go
Main is a simple test implementation which should convert an array of strings to an array of ints where each member of the result is the length of the corresponding string in the input array.
package main
import(
"fmt"
"./Mr"
)
func exfunc(i int, c chan int){
c<-i
}
func main(){
data := make(map[int]string)
data[1]="these"
data[2]="are"
data[3]="some"
data[4]="words"
data[5]="and a few more..."
f := func(w string)int{
return(len(w))
}
testMr := Mr.Map(f,data) // this is line 22 (matters later)
fmt.Println(testMr)
}
Which works great with my Mr.Map function given that I specify all the types explicitly.
package Mr
type result struct{
key,value int
}
func wrapper(f func(string) int,k int,v string, c chan result){
c <- result{k,f(v)}
}
func Map(f func(string) int,m map[int]string) map[int]int{
c := make(chan result)
ret := make(map[int]int)
n := 0
for k := range m{
go wrapper(f,k,m[k],c)
n++
}
for ;n>0; {
r := <-c
ret[r.key]=r.value
n--
}
return(ret)
}
However I was hoping that I would be able to generalize this mapping with the empty interface.
package Mr
type T interface{}
type result struct{
key,value T
}
func wrapper(f func(T) T,k T,v T, c chan result){
c <- result{k,f(v)}
}
func Map(f func(T) T,m map[T]T) map[T]T{
c := make(chan result)
ret := make(map[T]T)
n := 0
for k := range m{
go wrapper(f,k,m[k],c)
n++
}
for ;n>0; {
r := <-c
ret[r.key]=r.value
n--
}
return(ret)
}
Unfortunately when I run main with this generalize Mr.Map I get the following error.
# command-line-arguments
./main.go:22: cannot use f (type func(string) int) as type func(Mr.T) Mr.T in argument to Mr.Map
./main.go:22: cannot use data (type map[int]string) as type map[Mr.T]Mr.T in argument to Mr.Map
So yeah, obviously I understand what the errors are telling me but it seems wild that I would have to re-write my Map function for each possible combination of key and value types.
Is there a work around here, or is this just the nature of the beast?
No real workaround there, that's the nature of the beast.
The language was designed after struggling with C++ for some time, and the idea of the creators was simplifying all non-vital things but at the same time make key additions to make the language more expressive.
You can read a bit about their reasoning here, which I believe is quite interesting even if you don't agree with all the decisions they made:
https://commandcenter.blogspot.com.ar/2012/06/less-is-exponentially-more.html
In your example, if you wanted to, you could make your maps and functions use interface{} (which by the way is called the empty interface and not "nil" interface).
But of course you would lose compile-time type checking and would have to add casts all around.
You can also try to find an interface to express the commonalities of the types you want to use (which might not be so easy or even possible at all), and then build your mapping API around that interface.
The philosophy of Go is not compatible with generalized functions such as is the style with popular dynamic languages. To properly inform the compiler of what you are trying to do, you should express your needed map through an interface or simply by writing it for each type you are using it with.
Mapping requires allocating an array, iterating through a collection, and adding to the array some data element for each element in the collection. If you need a map for a slice of structs, as is common in the application layer, you can express this tersely in Go:
https://play.golang.org/p/pk3Tl_BdlD
Dynamic languages build a "type tree" of "generic" types that allow for terse programming, such as functions like map being called by one symbol over any possible type. This provides a ton of developer productivity because code can be written loosely to allow easy experimentation.
Go is designed for writing semi-permanent software. It performs well because it requires more information to be supplied to the compiler. Map is only about three lines of code, so the cost/benefit of developer productivity v. efficiency lands on the performance side for Go. Functions like map, reduce and filter should be written explicitly as needed.
To evaluate the language, I would encourage you to try to solve a problem with a Go program and see where that takes you.

golang: Can I apply helper function to one of the returned arguments

Let say that I have
connection := pool.GetConnection().(*DummyConnection)
where pool.GetConnection returns interface{} and I would like to cast it to DummyConnection.
I would like to change the GetConnection interface to return error. The code starts looking like this:
connectionInterface, err := pool.GetConnection()
connection := connectionInterface.(*DummyConnection)
I am wondering, can I avoid the need of helper variable and have these on a single line?
You cannot combine those two statements because the function returns a pair of values and there is no way to state which of them you would like to do the type assertion on. With the assignment it works because the identifiers are ordered as are the the return values, but how do you expect the compiler to infer which value you'd like to execute the type assertion on?
I wouldn't recommend trying to reduce your code too much in Go. It's not really consistent with how the language is designed and I believe that is deliberate. The philosophy is that this is easier to read because there isn't much abstraction and also because you're not given so many options to achieve the same result. Anyway, you wouldn't really be saving much with that type assertion and any function call like this requires a few additional lines of code for error handling. It's pretty much the norm in Go.
a solution in some kind. not reduce the code, but reduce variables in out function scope, by moving it to a anonymous inner function.
package main
import "fmt"
type t struct{}
func foo()(interface{},error){
return &t{},nil
}
func main() {
var myT *t
myT, err := func() (*t,error){
i,e:=foo()
return i.(*t),e
}()
fmt.Println(myT,err)
}

Resources