0

I have 2 variables with similar names in two different functions and inside of them I get variable's address using &.

Question is: is it possible that it will get a memory address of a variable inside the second function

2
  • 3
    The answer is an unmistakable no, even if the names of those variables were not just similar but identical, even then, as long as they are local to their functions (i.e. not global and shared), then the address would be different for both variables. Commented Jul 24, 2021 at 12:41
  • @mkopriva okay thanks Commented Jul 24, 2021 at 12:47

1 Answer 1

2

If those functions do not call each other, it's possible that calling one, the address will be x, then if the function returns (and the variable does not escape) and the other function is called, the same x address may be reused; but only if the other variable is not live (reachable) anymore. Whether this may be the case is not clear from your question.

Go has automatic memory management. Unless you touch package unsafe, you should not worry about pointers and addresses, it's safe to take and even to return addresses of local variables. The same memory will not be reused if a variable using that memory is still reachable.

One exception is variables that have 0 size. As per the spec, variables having zero size may or may not have the same address. In practice this causes no trouble as you can't change the value of such variables as they cannot store different values, but you can't assume anything about their memory addresses.

Sign up to request clarification or add additional context in comments.

2 Comments

No they don't call each other. It's just a REST api and these functions handle different routes. I just use variables like "phone" and "id" in Scan after I select them from database. So I have some Scan(&id) expressions and it disturbs me that they can be misinterpreted
As mentioned in the answer: Go has automatic memory management. You don't have to worry about that. The memory will not be reused for another variable for as long as the current variable is reachable.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.