get pointer to variable stored in reflect.Value in Golang [closed] - go

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 28 days ago.
Improve this question
Probably this is question is very simple, but i've spent some time and was not able to find any good solution(
For example we have the following code:
var someValue int = 10
v := reflect.ValueOf(someValue)
var v1 reflect.Value // should refer to &someValue, but with using of the "v" variable only
I know that the easiest solution will be v1 := reflect.ValueOf(&someValue) or using of reflect.New() function, but unfortunately this will not work in my case.
The "v1" variable should be initialized only with using of the "v" variable.

When you call reflect.ValueOf(someValue), ValueOf is passed a copy of someValue. The address of the argument to ValueOf is different from the address of someValue at the call site.
Whatever ValueOf returns cannot possibly know about the address of the original someValue, so what you want to achieve here is impossible.
The best you can do is call Value.Addr, which will return a reflect.Value representing the address of the copy of someValue that was passed to ValueOf:
var someValue int = 10
v := reflect.ValueOf(someValue)
v1 := v.Addr() // reflect.Value representing a *int pointing to a copy of someValue
var p1 *int = v1.Interface().(*int) // distinct from &someValue

Related

go lang map not throwing null pointer [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 months ago.
Improve this question
why this program is not throwing any null pointer exception
https://go.dev/play/p/37reql6Pdb5
eventhough m is null, still accessing on m.
Check out this code snippet:
package main
import "fmt"
func main() {
var m map[string]string = nil
fmt.Println(m) // output: "map[]"
}
This is an intended behavior since nil acts as zero value for many types of variables, including (but not limited to) maps and slices.
Also, there's no such thing in Golang as "Exception". You can check if a value exists in your map using this syntax:
value, found := m["key"]
where the found variable indicates if the value exists in the map.

cannot use a (type [10]string) as type []string in argument to strings.Join [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
i am trying to pass a array with fix size into a string.join function. how can i pass array with define index into string.join function
program
package main
import(
"fmt"
"strings"
)
func main() {
var a [10]string
fmt.Println("emp:", a)
a[2] = "hello"
a[4] = "member of"
a[8] = "google"
str2 := strings.Join(a, " ")
fmt.Println(str2)
}
output
cannot use a (type [10]string) as type []string in argument to strings.Join
do i need to convet it in []string or any other solution is posible
strings.Join expects the argument to be slice. So, you need to convert the string array to slice like below
...
str2 := strings.Join(a[:], " ")
...

"assignment to entry in nil map" with simple interface assignment not working [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I try to get myself familiarise with interface{} in Go. I tried:
var m map[string]string
m["time"] = "asdf"
and get error:
assignment to entry in nil map
I am not sure why I get the error.
When you declare a variable like this:
var m map[string]string
your m variable is assigned with a default value of map, which is nil, not an empty map. This is why you get that error, you are trying to add a value to a nil map.
To initialize an empty map, you can try any of these:
var m map[string]string = map[string]string{}
m := make(map[string]string)
m := map[string]string{}
Here is an article on default values for all Go types.
You need to use make(built-in function) like
make(map[string]string, 0)
to initialize the map
https://golang.org/doc/effective_go.html#allocation_make
https://golang.org/doc/effective_go.html#maps
The value of map m is nil.
The make function allocates and initializes a hash map data structure and returns a map value that points to it.
m := make(map[string]string)
m["time"] = "asdf"
Read allocations with make section of specs.

Go newbie: Getting "mismatched types *int and int" error when trying to compare reference to static integer [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I'm learning Go and trying to use reference to integer value in if-clause.
package main
import (
"fmt"
)
func main() {
a := 19
b := &a
if b > 10 {
fmt.Println("Its bigger")
}
}
This gives error message for type mismath.
How could I successfully compare value which b is referencing. In my training code I'm reading command line arguments with flags, but I suppose this example is reprex.
How should I compare when havin only reference available?
Here b is a pointer of int means *int. You can't compare *int type with int type.
Use *b to dereference to get the value and then compare with constant value.
if *b > 10 {
fmt.Println("Its bigger")
}

Why is the golang range operator implemented with declaration of a local variable? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
When looping using the golang range operator combined with the address-of & operator we can get a somewhat unexpected behaviour.
Take the example:
list := []int{1, 2}
pointerList := []*int{}
for _, value := range list {
pointerList = append(pointerList, &value)
}
fmt.Print(*pointerList[0], *pointerList[1])
// Prints: 2 2
This prints 2 2 because the variable value is only declared once and will change value for each iteration (while the address of value stays the same).
Q: Why does the go compiler not interpret the above code as if value was replaced by list[i], like so:
list := []int{1, 2}
pointerList := []*int{}
for i := range list {
pointerList = append(pointerList, &list[i])
}
fmt.Print(*pointerList[0], *pointerList[1])
// Prints: 1 2
If I'm not mistaken it is possible to do this interpretation for any use of range in a for loop. The behaviour seems more predictable and should be more performant if iterating over large objects (no extra copying to the local variable).
The example code:
https://play.golang.org/p/y89nMxVgBEs
https://play.golang.org/p/qHnJXMuHKdJ
Go does not have reference variables.
It is not possible to create a Go program where two variables share the same storage location in memory. It is possible to create two variables whose contents point to the same storage location, but that is not the same thing as two variables who share the same storage location.
Since list is an slice of int and not a slice of *int, there should not be any expectation that the address of value := list[i] would be the same as the address of list[i]. Since we already know that value is a copy, and that modifying it in any way won't affect list[i], it is far more performant to allocate the memory for an int once, and overwrite it each iteration of the loop, than to allocate a new int every iteration, and garbage collect the old one.

Resources