Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Name & value - Go vs Python

Tags:

python

go

In python, with below code,

x = 3
x='str'

allows x to first point to int type object and then to str type object, because python is dynamic typed. type(x) gives type of value(3 or str) but not type of name x.

In-fact, x does not store value 3 but point to int type object whose value is 3


In GO language, with below syntax,

func main() {
        y := 2
        fmt.Println(reflect.TypeOf(y)) // gives 'int'
        y = "str" // Compile time error, because GO is static typed 
}

Question:

Is int, the type of name y or the type of value 2?

like image 692
overexchange Avatar asked May 22 '26 18:05

overexchange


1 Answers

Python variables are bound to instances of classes that are assigned to them dynamically over the course of the program. Therefore, and especially with mutable objects, they are merely pointers who contain information about their data location and the type of the data they point to. That's why, upon assigning a new value, you are creating a new instance (which is your main interest) and bind the variable name to it, so the type is related to the value, not the variable itself.

>>> x = 3; id(x)
1996006560
>>> x = 'str'; id(x)
1732654458784

Go variables on the other hand, are serving (when not pointers) as stronghold memory locations, as the language is compiled and the variables get a constant "job" to keep a certain type of information (which could be a pointer as well). Therefore, a variable would almost certainly maintain his memory along the program, will have constant datatype properties, and, you could say the variable itself is of a certain type (and not of a semi-pointer type).

package main
import . "fmt"
func main () {
    x := "str"; Println(&x)         // 0xc04203a1c0
    x = "Hello world!"; Println(&x) // 0xc04203a1c0
}
like image 93
Uriel Avatar answered May 25 '26 12:05

Uriel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!